Selaa lähdekoodia

更新方法调用

ting.yin 8 vuotta sitten
vanhempi
commit
7265c51318

+ 4 - 0
exam-work-api/pom.xml

@@ -43,6 +43,10 @@
             <groupId>com.google.code.gson</groupId>
             <artifactId>gson</artifactId>
             <version>2.8.0</version>
+        </dependency>
+		<dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi-ooxml</artifactId>
         </dependency>
     </dependencies>
 

+ 10 - 7
exam-work-api/src/main/java/cn/com/qmth/examcloud/service/examwork/api/ExamApi.java

@@ -4,8 +4,10 @@ import cn.com.qmth.examcloud.service.examwork.dao.ExamRepo;
 import cn.com.qmth.examcloud.service.examwork.entity.Exam;
 import cn.com.qmth.examcloud.service.examwork.service.ExamService;
 import io.swagger.annotations.ApiOperation;
+
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.domain.PageRequest;
+import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.*;
 
@@ -28,43 +30,44 @@ public class ExamApi {
     @ApiOperation(value="查询所有考试批次",notes = "分页带查询")
     @GetMapping("/exam/all/{curPage}/{pageSize}")
     public ResponseEntity getAllExam(@ModelAttribute Exam examCriteria, @PathVariable Integer curPage,@PathVariable Integer pageSize){
-        return examService.getAllExam(examCriteria,new PageRequest(curPage - 1,pageSize));
+    	return new ResponseEntity(examService.getAllExam(examCriteria,new PageRequest(curPage - 1,pageSize)), HttpStatus.OK);
     }
 
     @ApiOperation(value="查询所有考试批次",notes = "不分页带查询")
     @GetMapping("/exam/all")
     public ResponseEntity getAllExam(@ModelAttribute Exam examCriteria){
-        return examService.getAllExam(examCriteria);
+        return new ResponseEntity(examService.getAllExam(examCriteria), HttpStatus.OK);
     }
 
     @ApiOperation(value="查询所有考试批次",notes = "不分页不带查询")
     @GetMapping("/exam")
     public ResponseEntity getAllExam(){
-        return examService.getAllExam();
+        return new ResponseEntity(examService.getAllExam(), HttpStatus.OK);
     }
 
     @ApiOperation(value="按ID查询考试批次",notes = "ID查询")
     @GetMapping("/exam/{id}")
     public ResponseEntity<Exam> getExamById(@PathVariable Long id){
-        return examService.getExamById(id);
+        return new ResponseEntity<Exam>(examService.getExamById(id),HttpStatus.OK);
     }
 
     @ApiOperation(value="新增考试批次",notes = "新增")
     @PostMapping("/exam")
     public ResponseEntity addExam(@RequestBody Exam exam){
         exam.setCreateTime(new Date());
-        return examService.saveExam(exam);
+        return new ResponseEntity(examService.saveExam(exam),HttpStatus.OK);
     }
 
     @ApiOperation(value="更新考试批次",notes = "更新")
     @PutMapping("/exam")
     public ResponseEntity updateExam(@RequestBody Exam exam){
-        return examService.saveExam(exam);
+        return new ResponseEntity(examService.saveExam(exam),HttpStatus.OK);
     }
 
     @ApiOperation(value="按ID删除考试批次",notes = "删除")
     @DeleteMapping("/exam/{id}")
     public ResponseEntity deleteExam(@PathVariable Long id){
-        return examService.deleteExam(id);
+    	examService.deleteExam(id);
+        return new ResponseEntity(HttpStatus.OK);
     }
 }

+ 25 - 6
exam-work-api/src/main/java/cn/com/qmth/examcloud/service/examwork/api/ExamStudentApi.java

@@ -1,14 +1,20 @@
 package cn.com.qmth.examcloud.service.examwork.api;
 
+import java.io.IOException;
+import java.util.List;
+
 import cn.com.qmth.examcloud.service.examwork.dao.ExamStudentRepo;
 import cn.com.qmth.examcloud.service.examwork.entity.ExamStudent;
 import cn.com.qmth.examcloud.service.examwork.service.ExamStudentService;
+import cn.com.qmth.examcloud.service.examwork.util.ExcelError;
 import io.swagger.annotations.ApiOperation;
+
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.domain.PageRequest;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
 import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
 
 /**
  * 考生服务API
@@ -27,13 +33,13 @@ public class ExamStudentApi {
     @ApiOperation(value="查询所有考试学生",notes = "分页")
     @GetMapping("/exam_student/all/{curPage}/{pageSize}")
     public ResponseEntity getAllExamStudent(@ModelAttribute ExamStudent examCriteria, @PathVariable Integer curPage, @PathVariable Integer pageSize){
-        return examStudentService.getAllExamStudent(examCriteria,new PageRequest(curPage - 1,pageSize));
+        return new ResponseEntity(examStudentService.getAllExamStudent(examCriteria,new PageRequest(curPage - 1,pageSize)),HttpStatus.OK);
     }
 
     @ApiOperation(value="查询所有考试学生",notes = "不分页")
     @GetMapping("/exam_student/all")
     public ResponseEntity getAllExamStudent(@ModelAttribute ExamStudent examCriteria){
-        return examStudentService.getAllExamStudent(examCriteria);
+        return new ResponseEntity(examStudentService.getAllExamStudent(examCriteria), HttpStatus.OK);
     }
 
     @ApiOperation(value="查询所有考试学生",notes = "不分页不带查询条件")
@@ -45,24 +51,37 @@ public class ExamStudentApi {
     @ApiOperation(value="按ID查询考试学生",notes = "ID查询")
     @GetMapping("/exam_student/{id}")
     public ResponseEntity<ExamStudent> getExamStudentById(@PathVariable Long id){
-        return examStudentService.getExamStudentById(id);
+        return new ResponseEntity<ExamStudent>(examStudentService.getExamStudentById(id),HttpStatus.OK);
     }
 
     @ApiOperation(value="新增考试学生",notes = "新增")
     @PostMapping("/exam_student")
     public ResponseEntity addExamStudent(@RequestBody ExamStudent examStudent){
-        return examStudentService.saveExamStudent(examStudent);
+        return new ResponseEntity<ExamStudent>(examStudentService.saveExamStudent(examStudent),HttpStatus.OK);
     }
 
     @ApiOperation(value="更新考试学生",notes = "更新")
     @PutMapping("/exam_student")
     public ResponseEntity updateExamStudent(@RequestBody ExamStudent examStudent){
-        return examStudentService.saveExamStudent(examStudent);
+        return new ResponseEntity(examStudentService.saveExamStudent(examStudent),HttpStatus.OK);
     }
 
     @ApiOperation(value="按ID删除考试学生",notes = "删除")
     @DeleteMapping("/exam_student/{id}")
     public ResponseEntity deleteExamStudent(@PathVariable Long id){
-        return examStudentService.deleteExamStudent(id);
+    	examStudentService.deleteExamStudent(id);
+        return new ResponseEntity(HttpStatus.OK);
+    }
+    
+    @ApiOperation(value="导入考试学生",notes = "导入")
+    @DeleteMapping("/exam_student/import")
+    public ResponseEntity importExamStudent(@RequestParam Long examId,@RequestParam MultipartFile file){
+    	try {
+    		List<ExcelError> excelErrors = examStudentService.importExamStudent(examId,file.getInputStream());
+    		return new ResponseEntity(excelErrors,HttpStatus.OK);
+		} catch (IOException e) {
+			e.printStackTrace();
+			return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
+		}
     }
 }

+ 20 - 19
exam-work-api/src/main/java/cn/com/qmth/examcloud/service/examwork/service/ExamService.java

@@ -1,16 +1,18 @@
 package cn.com.qmth.examcloud.service.examwork.service;
 
-import cn.com.qmth.examcloud.service.examwork.dao.ExamRepo;
-import cn.com.qmth.examcloud.service.examwork.entity.Exam;
+import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith;
+
+import java.util.List;
+
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.domain.Example;
 import org.springframework.data.domain.ExampleMatcher;
+import org.springframework.data.domain.Page;
 import org.springframework.data.domain.Pageable;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
 
-import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith;
+import cn.com.qmth.examcloud.service.examwork.dao.ExamRepo;
+import cn.com.qmth.examcloud.service.examwork.entity.Exam;
 
 /**
  * 考试批次服务类
@@ -27,30 +29,31 @@ public class ExamService {
      * @param pageable
      * @return
      */
-    public ResponseEntity getAllExam(Exam examCriteria, Pageable pageable){
+    public Page<Exam> getAllExam(Exam examCriteria, Pageable pageable){
         ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                 .withMatcher("name",startsWith());
         Example<Exam> examExample = Example.of(examCriteria, exampleMatcher);
-        return new ResponseEntity(examRepo.findAll(examExample,pageable), HttpStatus.OK);
+        return examRepo.findAll(examExample,pageable);
     }
 
     /**
      * 获取所有考试批次
      * @param examCriteria
+     * @return 
      * @return
      */
-    public ResponseEntity getAllExam(Exam examCriteria){
+    public List<Exam> getAllExam(Exam examCriteria){
 //        ExampleMatcher exampleMatcher = ExampleMatcher.matching();
         Example<Exam> examExample = Example.of(examCriteria);
-        return new ResponseEntity(examRepo.findAll(examExample), HttpStatus.OK);
+        return examRepo.findAll(examExample);
     }
 
     /**
      * 获取所有考试批次
      * @return
      */
-    public ResponseEntity getAllExam(){
-        return new ResponseEntity(examRepo.findAll(), HttpStatus.OK);
+    public List<Exam> getAllExam(){
+        return examRepo.findAll();
     }
 
     /**
@@ -58,8 +61,8 @@ public class ExamService {
      * @param examId
      * @return
      */
-    public ResponseEntity<Exam> getExamById(Long examId){
-        return new ResponseEntity<Exam>(examRepo.findOne(examId),HttpStatus.OK);
+    public Exam getExamById(Long examId){
+        return examRepo.findOne(examId);
     }
 
     /**
@@ -67,8 +70,8 @@ public class ExamService {
      * @param exam
      * @return
      */
-    public ResponseEntity saveExam(Exam exam){
-        return new ResponseEntity(examRepo.save(exam),HttpStatus.OK);
+    public Exam saveExam(Exam exam){
+        return examRepo.save(exam);
     }
 
     /**
@@ -76,17 +79,15 @@ public class ExamService {
      * @param examId
      * @return
      */
-    public ResponseEntity deleteExam(Long examId){
+    public void deleteExam(Long examId){
         examRepo.delete(examId);
-        return new ResponseEntity(HttpStatus.OK);
     }
 
     /**
      * 删除所有考试批次
      * @return
      */
-    public ResponseEntity deleteAllExam(){
+    public void deleteAllExam(){
         examRepo.deleteAll();
-        return new ResponseEntity(HttpStatus.OK);
     }
 }

+ 65 - 19
exam-work-api/src/main/java/cn/com/qmth/examcloud/service/examwork/service/ExamStudentService.java

@@ -1,15 +1,25 @@
 package cn.com.qmth.examcloud.service.examwork.service;
 
-import cn.com.qmth.examcloud.service.examwork.dao.ExamStudentRepo;
-import cn.com.qmth.examcloud.service.examwork.entity.ExamStudent;
+import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith;
+
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.data.domain.Example;
 import org.springframework.data.domain.ExampleMatcher;
+import org.springframework.data.domain.Page;
 import org.springframework.data.domain.Pageable;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
-import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.startsWith;
+
+import cn.com.qmth.examcloud.service.examwork.dao.ExamRepo;
+import cn.com.qmth.examcloud.service.examwork.dao.ExamStudentRepo;
+import cn.com.qmth.examcloud.service.examwork.entity.Exam;
+import cn.com.qmth.examcloud.service.examwork.entity.ExamStudent;
+import cn.com.qmth.examcloud.service.examwork.util.ExcelError;
+import cn.com.qmth.examcloud.service.examwork.util.ExcelReader;
+import cn.com.qmth.examcloud.service.examwork.util.ExcelReaderHandle;
 
 /**
  * 考试学生服务类
@@ -19,30 +29,34 @@ import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatc
 public class ExamStudentService {
     @Autowired
     ExamStudentRepo examStudentRepo;
+    @Autowired
+    ExamRepo examRepo;
 
     /**
      * 获取所有考试学生(分页)
      * @param examCriteria
      * @param pageable
+     * @return 
      * @return
      */
-    public ResponseEntity getAllExamStudent(ExamStudent examCriteria, Pageable pageable){
+    public  Page<ExamStudent> getAllExamStudent(ExamStudent examCriteria, Pageable pageable){
         ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                 .withMatcher("name",startsWith());
         Example<ExamStudent> examExamStudentple = Example.of(examCriteria, exampleMatcher);
-        return new ResponseEntity(examStudentRepo.findAll(examExamStudentple,pageable), HttpStatus.OK);
+        return examStudentRepo.findAll(examExamStudentple,pageable);
     }
 
     /**
      * 获取所有考试学生
      * @param examCriteria
+     * @return 
      * @return
      */
-    public ResponseEntity getAllExamStudent(ExamStudent examCriteria){
+    public  List<ExamStudent> getAllExamStudent(ExamStudent examCriteria){
         ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                 .withMatcher("name",startsWith());
         Example<ExamStudent> examExamStudentple = Example.of(examCriteria, exampleMatcher);
-        return new ResponseEntity(examStudentRepo.findAll(examExamStudentple), HttpStatus.OK);
+        return examStudentRepo.findAll(examExamStudentple);
     }
 
     /**
@@ -50,17 +64,18 @@ public class ExamStudentService {
      * @param studentId
      * @return
      */
-    public ResponseEntity<ExamStudent> getExamStudentById(Long studentId){
-        return new ResponseEntity<ExamStudent>(examStudentRepo.findOne(studentId),HttpStatus.OK);
+    public ExamStudent getExamStudentById(Long studentId){
+        return examStudentRepo.findOne(studentId);
     }
 
     /**
      * 按考试批次获取学生
      * @param examId
+     * @return 
      * @return
      */
-    public ResponseEntity getExamStudentByExamId(Long examId,Pageable pageable){
-        return new ResponseEntity(examStudentRepo.findByExamId(examId,pageable),HttpStatus.OK);
+    public Page<ExamStudent> getExamStudentByExamId(Long examId,Pageable pageable){
+        return examStudentRepo.findByExamId(examId,pageable);
     }
 
     /**
@@ -68,8 +83,8 @@ public class ExamStudentService {
      * @param exam
      * @return
      */
-    public ResponseEntity saveExamStudent(ExamStudent exam){
-        return new ResponseEntity(examStudentRepo.save(exam),HttpStatus.OK);
+    public ExamStudent saveExamStudent(ExamStudent exam){
+        return examStudentRepo.save(exam);
     }
 
     /**
@@ -77,17 +92,48 @@ public class ExamStudentService {
      * @param examId
      * @return
      */
-    public ResponseEntity deleteExamStudent(Long examId){
+    public void deleteExamStudent(Long examId){
         examStudentRepo.delete(examId);
-        return new ResponseEntity(HttpStatus.OK);
     }
 
     /**
      * 删除所有考试学生
      * @return
      */
-    public ResponseEntity deleteAllExamStudent(){
+    public void deleteAllExamStudent(){
         examStudentRepo.deleteAll();
-        return new ResponseEntity(HttpStatus.OK);
     }
+    
+    /**
+     * 导入考试学生
+     * @return
+     */
+	public List<ExcelError> importExamStudent(Long examId, InputStream inputStream) {
+		Exam exam = examRepo.findOne(examId);
+		List<ExamStudent> examStudents = new ArrayList<ExamStudent>();
+		ExcelReader excelReader = new ExcelReader(ExamStudent.class);
+        List<ExcelError> excelErrors = excelReader.reader(inputStream, new ExcelReaderHandle() {
+            @Override
+            public ExcelError handle(Object obj) {
+                ExamStudent dto = (ExamStudent) obj;
+                dto.setRootOrgId(exam.getOrgId());
+                dto.setExam(exam);
+                ExcelError error = importCheck(dto);
+                if (error == null) {
+                	examStudents.add(dto);
+                }
+                return error;
+            }
+        });
+        examStudentRepo.save(examStudents);
+        return excelErrors;
+	}
+	/**
+	 * 考生导入验证
+	 * @param stu
+	 * @return
+	 */
+	public ExcelError importCheck(ExamStudent dto){
+		return null;
+	}
 }

+ 57 - 0
exam-work-api/src/main/java/cn/com/qmth/examcloud/service/examwork/util/ColumnSetting.java

@@ -0,0 +1,57 @@
+package cn.com.qmth.examcloud.service.examwork.util;
+
+public class ColumnSetting implements Comparable<ColumnSetting> {
+
+    private String header;
+    private String fieldName;
+    private int width;
+    private int index;
+
+    public ColumnSetting(String header,String fieldName, int width, int index) {
+        this.header = header;
+        this.fieldName = fieldName;
+        this.width = width;
+        this.index = index;
+    }
+
+    public String getHeader() {
+        return header;
+    }
+
+    public void setHeader(String header) {
+        this.header = header;
+    }
+
+    public int getWidth() {
+        return width;
+    }
+
+    public void setWidth(int width) {
+        this.width = width;
+    }
+
+    public int getIndex() {
+        return index;
+    }
+
+    public void setIndex(int index) {
+        this.index = index;
+    }
+
+    public String getFieldName() {
+		return fieldName;
+	}
+
+	public void setFieldName(String fieldName) {
+		this.fieldName = fieldName;
+	}
+
+	@Override
+    public int compareTo(ColumnSetting columnSetting) {
+        if (index < columnSetting.getIndex())
+            return - 1 ;
+        if (index > columnSetting.getIndex())
+            return 1 ;
+        return 0 ;
+    }
+}

+ 48 - 0
exam-work-api/src/main/java/cn/com/qmth/examcloud/service/examwork/util/ExcelError.java

@@ -0,0 +1,48 @@
+package cn.com.qmth.examcloud.service.examwork.util;
+/**
+ * 
+ * @Description: excel导入错误
+ * @author ting.yin
+ * @date 2016年8月19日
+ */
+public class ExcelError {
+
+	/**
+	 * 错误行数
+	 */
+	private int row;
+
+	/**
+	 * 错误类型
+	 */
+	private String excelErrorType;
+
+	public ExcelError() {
+
+	}
+
+	public ExcelError(int row, String excelErrorType) {
+		this.row = row;
+		this.excelErrorType = excelErrorType;
+	}
+	
+	public ExcelError(String excelErrorType) {
+		this.excelErrorType = excelErrorType;
+	}
+	public int getRow() {
+		return row;
+	}
+
+	public void setRow(int row) {
+		this.row = row;
+	}
+
+	public String getExcelErrorType() {
+		return excelErrorType;
+	}
+
+	public void setExcelErrorType(String excelErrorType) {
+		this.excelErrorType = excelErrorType;
+	}
+
+}

+ 31 - 0
exam-work-api/src/main/java/cn/com/qmth/examcloud/service/examwork/util/ExcelProperty.java

@@ -0,0 +1,31 @@
+package cn.com.qmth.examcloud.service.examwork.util;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target(ElementType.FIELD)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface ExcelProperty {
+	/**
+	 * 导出时列名
+	 */
+    String name() default "";
+    
+	/**
+	 * 导出时列宽
+	 */
+    int width() default 0;
+	/**
+	 * 排序
+	 */
+    int index();
+    /**
+     * 类型
+     * 0:导入(读excel)
+     * 1:导出(写excel)
+     * 2:导入&导出
+     */
+    int type() default 2;
+}

+ 89 - 0
exam-work-api/src/main/java/cn/com/qmth/examcloud/service/examwork/util/ExcelReader.java

@@ -0,0 +1,89 @@
+package cn.com.qmth.examcloud.service.examwork.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
+import org.apache.poi.ss.usermodel.*;
+
+/**
+ * 
+ * @Description: 读取excel
+ * @author ting.yin
+ * @date 2016年8月19日
+ */
+public class ExcelReader extends ExcelUtils {
+
+	public ExcelReader(Class<?> dataClass) {
+		super(dataClass,true);
+	}
+
+	/**
+	 * 
+	 * @param inputStream
+	 *            输入流
+	 * @param handle
+	 *            单个对象处理器
+	 * @return 错误信息集合
+	 */
+	public List<ExcelError> reader(InputStream inputStream,
+			ExcelReaderHandle handle) {
+		List<ExcelError> excelErrors = new ArrayList<ExcelError>();
+		try {
+			Workbook wb = WorkbookFactory.create(inputStream);
+			Sheet sheet = wb.getSheetAt(0);
+			for (int i = 1; i <= sheet.getLastRowNum(); i++) {
+				Row row = sheet.getRow(i);
+				if (row == null) {
+					return excelErrors;
+				}
+				Object dto = getDataClass().newInstance();
+//				FieldAccess access = FieldAccess.get(getDataClass());
+				for (int j = 0; j < this.getColumnSettings().size(); j++) {
+					ColumnSetting columnSetting = this.getColumnSettings().get(j);
+					Cell cell = row.getCell(columnSetting.getIndex());
+					Object obj = convert(cell);
+					Field field = getDataClass().getDeclaredField(columnSetting.getFieldName());
+					field.setAccessible(true);
+					field.set(dto, obj);
+				}
+				ExcelError error = handle.handle(dto);
+				if (error != null) {
+					error.setRow(i+1);
+					excelErrors.add(error);
+				}
+			}
+		}catch (InvalidFormatException e) {
+				e.printStackTrace();
+		} catch (IOException e) {
+			e.printStackTrace();
+		} catch (Exception e) {
+			e.printStackTrace();
+		} finally {
+			try {
+				inputStream.close();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+		return excelErrors;
+	}
+
+	private Object convert(Cell cell) {
+		if(cell!=null){
+			switch (cell.getCellType()) {
+			case Cell.CELL_TYPE_STRING:
+				return cell.getStringCellValue().toString();
+			case Cell.CELL_TYPE_BOOLEAN:
+				return String.valueOf(cell.getBooleanCellValue());
+			case Cell.CELL_TYPE_NUMERIC:
+				return Math.round(cell.getNumericCellValue());
+			}
+		}
+		
+		return null;
+	}
+}

+ 7 - 0
exam-work-api/src/main/java/cn/com/qmth/examcloud/service/examwork/util/ExcelReaderHandle.java

@@ -0,0 +1,7 @@
+package cn.com.qmth.examcloud.service.examwork.util;
+
+public interface ExcelReaderHandle {
+	
+	ExcelError handle(Object dto);
+
+}

+ 70 - 0
exam-work-api/src/main/java/cn/com/qmth/examcloud/service/examwork/util/ExcelUtils.java

@@ -0,0 +1,70 @@
+package cn.com.qmth.examcloud.service.examwork.util;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * Created by zhengmin on 2016/8/17.
+ */
+@SuppressWarnings("rawtypes")
+public abstract class ExcelUtils {
+
+	private Class dataClass;
+    private List<ColumnSetting> columnSettings;
+    
+    public ExcelUtils(Class<?> dataClass , boolean isRead){
+        this.dataClass = dataClass;
+        this.columnSettings = getColumnSettings(dataClass,isRead);
+    }
+
+    public Class getDataClass() {
+        return dataClass;
+    }
+
+    public void setDataClass(Class dataClass) {
+        this.dataClass = dataClass;
+    }
+
+    public List<ColumnSetting> getColumnSettings() {
+        return columnSettings;
+    }
+
+    public void setColumnSettings(List<ColumnSetting> columnSettings) {
+        this.columnSettings = columnSettings;
+    }
+
+    /**
+     * 提取ExcelProperty注解类的字段信息
+     * @param dataClass 需要解析excel的数据类型
+     * @return
+     */
+    protected List<ColumnSetting> getColumnSettings(Class<?> dataClass, boolean isRead){
+		List<ColumnSetting> columnSettings = new ArrayList<>();
+		Field[] fileds = dataClass.getDeclaredFields();
+		for (Field field : fileds) {
+			ExcelProperty exportProperty = field.getAnnotation(ExcelProperty.class);
+			if (exportProperty != null) {
+				if (isRead) {
+					if (exportProperty.type() == 0 || exportProperty.type() == 2) {
+						ColumnSetting columnSetting = new ColumnSetting(
+								exportProperty.name(),field.getName(),exportProperty.width(),
+								exportProperty.index());
+						columnSettings.add(columnSetting);
+					}
+				}else{
+					if (exportProperty.type() == 1 || exportProperty.type() == 2) {
+						ColumnSetting columnSetting = new ColumnSetting(
+								exportProperty.name(), field.getName(),exportProperty.width(),
+								exportProperty.index());
+						columnSettings.add(columnSetting);
+					}
+				}
+			}
+		}
+		Collections.sort(columnSettings);
+		return columnSettings;
+    }
+    
+}

+ 187 - 0
exam-work-api/src/main/java/cn/com/qmth/examcloud/service/examwork/util/ExcelWriter.java

@@ -0,0 +1,187 @@
+package cn.com.qmth.examcloud.service.examwork.util;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.lang.reflect.Field;
+import java.text.SimpleDateFormat;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.poi.xssf.usermodel.*;
+
+/**
+ * Created by dizhi on 2016/6/19.
+ */
+public class ExcelWriter extends ExcelUtils{
+
+
+    public ExcelWriter(Class<?> dataClass){
+        super(dataClass,false);
+    }
+
+    /**
+     * 写入excel
+     * @param sheetName sheet名称
+     * @param dataset 数据集合
+     * @param out 输出流
+     */
+    public void write(String sheetName,Collection<?> dataset, OutputStream out) {
+        // 声明一个工作薄
+        XSSFWorkbook workbook = new XSSFWorkbook();
+        // 生成一个表格
+        XSSFSheet sheet = workbook.createSheet(sheetName);
+
+        // 设置表格默认列宽度为15个字节
+        sheet.setDefaultColumnWidth((short) 15);
+        // 生成一个样式
+        XSSFCellStyle style = workbook.createCellStyle();
+        // 设置这些样式
+//        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
+//        style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
+//        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
+//        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
+//        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
+//        style.setBorderTop(XSSFCellStyle.BORDER_THIN);
+//        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
+        // 生成一个字体
+//        XSSFFont font = workbook.createFont();
+//        font.setColor(HSSFColor.VIOLET.index);
+//        font.setFontHeightInPoints((short) 12);
+//        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
+//        // 把字体应用到当前的样式
+//        style.setFont(font);
+//        // 生成并设置另一个样式
+//        XSSFCellStyle style2 = workbook.createCellStyle();
+//        style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
+//        style2.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
+//        style2.setBorderBottom(XSSFCellStyle.BORDER_THIN);
+//        style2.setBorderLeft(XSSFCellStyle.BORDER_THIN);
+//        style2.setBorderRight(XSSFCellStyle.BORDER_THIN);
+//        style2.setBorderTop(XSSFCellStyle.BORDER_THIN);
+//        style2.setAlignment(XSSFCellStyle.ALIGN_CENTER);
+//        style2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
+//        // 生成另一个字体
+//        XSSFFont font2 = workbook.createFont();
+//        font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
+        // 把字体应用到当前的样式
+        //style2.setFont(font2);
+
+        // 声明一个画图的顶级管理器
+        //HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
+        // 定义注释的大小和位置,详见文档
+//        XSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
+//                0, 0, 0, (short) 4, 2, (short) 6, 5));
+//        // 设置注释内容
+//        comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));
+//        // 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.
+//        comment.setAuthor("leno");
+
+        List<ColumnSetting> columnSettings = this.getColumnSettings();
+
+        // 产生表格标题行
+        XSSFRow row = sheet.createRow(0);
+        for (short i = 0; i < columnSettings.size(); i++) {
+            XSSFCell cell = row.createCell(i);
+            cell.setCellStyle(style);
+            XSSFRichTextString text = new XSSFRichTextString(columnSettings.get(i).getHeader());
+            cell.setCellValue(text);
+            if(columnSettings.get(i).getWidth() > 0){
+                sheet.setColumnWidth(i,columnSettings.get(i).getWidth()*256);
+            }
+        }
+
+        // 遍历集合数据,产生数据行
+        //Iterator<?> it = dataset.iterator();
+        int index = 0;
+        for(Object obj : dataset) {
+            index++;
+            row = sheet.createRow(index);
+            //T t = (T) it.next();
+            // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
+            for (short i = 0; i < columnSettings.size(); i++) {
+                XSSFCell cell = row.createCell(i);
+                //cell.setCellStyle(style2);
+                String fieldName = columnSettings.get(i).getFieldName();
+
+                try {
+                	Field field=this.getDataClass().getDeclaredField(fieldName);
+                	field.setAccessible(true);
+                    Object value = field.get(obj);
+                    // 判断值的类型后进行强制类型转换
+                    String textValue = null;
+                    // if (value instanceof Integer) {
+                    // int intValue = (Integer) value;
+                    // cell.setCellValue(intValue);
+                    // } else if (value instanceof Float) {
+                    // float fValue = (Float) value;
+                    // textValue = new HSSFRichTextString(
+                    // String.valueOf(fValue));
+                    // cell.setCellValue(textValue);
+                    // } else if (value instanceof Double) {
+                    // double dValue = (Double) value;
+                    // textValue = new HSSFRichTextString(
+                    // String.valueOf(dValue));
+                    // cell.setCellValue(textValue);
+                    // } else if (value instanceof Long) {
+                    // long longValue = (Long) value;
+                    // cell.setCellValue(longValue);
+                    // }
+                    if (value instanceof Boolean) {
+                        boolean bValue = (Boolean) value;
+                        textValue = "是";
+                        if (!bValue) {
+                            textValue = "否";
+                        }
+                    } else if (value instanceof Date) {
+                        Date date = (Date) value;
+                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+                        textValue = sdf.format(date);
+                    }
+                    else {
+                        // 其它数据类型都当作字符串简单处理
+                        textValue = String.valueOf(value);
+                    }
+                    // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
+                    if (textValue != null) {
+                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
+                        Matcher matcher = p.matcher(textValue);
+                        if (matcher.matches()) {
+                            // 是数字当作double处理
+                            cell.setCellValue(Double.parseDouble(textValue));
+                        } else {
+                            XSSFRichTextString richString = new XSSFRichTextString(
+                                    textValue);
+
+                            cell.setCellValue(richString);
+                        }
+                    }
+                } catch (NoSuchFieldException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                } catch (IllegalAccessException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                } catch (SecurityException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                } catch (IllegalArgumentException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                } finally {
+                    // 清理资源
+                }
+            }
+            
+        }
+        try {
+            workbook.write(out);
+        } catch (IOException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        }
+
+    }
+}

+ 34 - 0
exam-work-api/src/main/java/cn/com/qmth/examcloud/service/examwork/util/ExportUtils.java

@@ -0,0 +1,34 @@
+package cn.com.qmth.examcloud.service.examwork.util;
+
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletResponse;
+import java.net.URLEncoder;
+import java.util.Collection;
+
+
+/*
+ * excel导出工具
+ */
+public class ExportUtils {
+
+    private static final String DEFALUT_CONTENT_TYPE = "application/vnd.ms-excel";
+
+    private static final String DEFALUT_EXT = ".xlsx";
+
+    public static void exportEXCEL(String fileName,Class<?> dataClass,
+                             Collection<?> dataset,HttpServletResponse response) {
+        try {
+        	
+            response.setHeader("Content-Disposition", "inline; filename="
+                    +URLEncoder.encode(fileName, "UTF-8") + DEFALUT_EXT);
+            response.setContentType(DEFALUT_CONTENT_TYPE);
+            ServletOutputStream outputStream = response.getOutputStream();
+            ExcelWriter excelExporter = new ExcelWriter(dataClass);
+            excelExporter.write("sheet1",dataset,outputStream);
+            outputStream.flush();
+            outputStream.close();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+}

+ 11 - 0
exam-work-domain/src/main/java/cn/com/qmth/examcloud/service/examwork/entity/Exam.java

@@ -22,6 +22,9 @@ public class Exam implements Serializable {
 	@Id
 	@GeneratedValue
 	private long id;
+	
+	@NotNull
+	private Long orgId;
 
 	@Temporal(value = TemporalType.DATE)
 	@DateTimeFormat(pattern="yyyy-MM-dd")
@@ -136,6 +139,14 @@ public class Exam implements Serializable {
 		this.createTime = createTime;
 	}
 
+	public Long getOrgId() {
+		return orgId;
+	}
+
+	public void setOrgId(Long orgId) {
+		this.orgId = orgId;
+	}
+
 	public Exam() {
 	}
 }