1. 批量导出到多个工作铺
@PostMapping("download")
public void download(HttpServletResponse response,
@RequestParam(value = "types") String types,
@RequestParam(value = "status", required = false) Integer status,
@RequestParam(value = "startTime", required = false) String startTime,
@RequestParam(value = "endTime", required = false) String endTime,
@RequestParam(value = "userId", required = false) Integer userId) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startTime1 = null;
Date endTime1 = null;
if (startTime != null && endTime != null) {
try {
startTime1 = sdf.parse(startTime);
endTime1 = sdf.parse(endTime);
} catch (ParseException e) {
e.printStackTrace();
}
}
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short) 18);
headWriteFont.setBold(true);
headWriteCellStyle.setWriteFont(headWriteFont);
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
WriteFont contentWriteFont = new WriteFont();
contentWriteFont.setFontHeightInPoints((short) 14);
contentWriteCellStyle.setWriteFont(contentWriteFont);
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
String fileName = URLEncoder.encode("业绩评定", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xls");
ExcelWriter excelWriter = null;
try {
excelWriter = EasyExcel.write(response.getOutputStream())
.excelType(XLS)
.registerWriteHandler(horizontalCellStyleStrategy)
.build();
List<String> typeList;
if (types.equals("all")) {
typeList = allList();
} else {
typeList = JSONArray.parseArray(types, String.class);
}
for (String type : typeList) {
WriteSheet writeSheet = EasyExcel.writerSheet(CommonUtils.excelName(type)).head(demoData(type)).build();
excelWriter.write(data(type, status, startTime1, endTime1, userId), writeSheet);
}
} finally {
if (excelWriter != null) {
excelWriter.finish();
}
}
}
2. 写入模板导出
@PostMapping("templateWrite")
public void templateWrite(HttpServletResponse response,
@RequestParam(value = "userId", required = false) Integer userId) throws IOException {
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String templateFileName = "/static/demo.xls";
String fileName = URLEncoder.encode("业绩总分一览表", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xls");
EasyExcel.write(response.getOutputStream(), AllScoresExcel.class)
.excelType(XLS)
.registerWriteHandler(horizontalCellStyleStrategy)
.withTemplate(new ClassPathResource(templateFileName).getInputStream())
.needHead(false)
.sheet()
.doWrite(allScoresDate(userId));
}
3. 批量导入
public RestResult<Object> tureOrFalse(MultipartFile file){
FileInputStream inputStream=null;
try {
inputStream = (FileInputStream) file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
EasyExcel.read(inputStream, ModelQuestion.class, new ModelQuestionListener(modelQuestionService)).headRowNumber(2).sheet().doRead();
return RestResult.ok(1,"aa");
}
4. 监听器
@Slf4j
public class ModelQuestionListener extends AnalysisEventListener<ModelQuestion> {
private static final int BATCH_COUNT = 1000;
List<ModelQuestion> list = new ArrayList<>();
private ModelQuestionService demoDAO;
public ModelQuestionListener(ModelQuestionService demoDAO) {
this.demoDAO = demoDAO;
}
@Override
public void invoke(ModelQuestion data, AnalysisContext context) {
log.info("解析到一条数据:{}", JSON.toJSONString(data));
if (data.getCourseId()!=null && data.getMajorId()!=null && data.getChapter()!=null && data.getQuestion()!=null && data.getAnswer()!=null && data.getDifficulty()!=null){
if (data.getParsing()==null){
data.setParsing("无");
}
list.add(data);
}
if (list.size() >= BATCH_COUNT) {
saveData();
list.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
saveData();
log.info("所有数据解析完成!");
}
private void saveData() {
log.info("{}条数据,开始存储数据库!", list.size());
demoDAO.insertList(list);
log.info("存储数据库成功!");
}
}
5. 数据格式化
public class JsonConverter implements Converter<String> {
@Override
public Class supportJavaTypeKey() {
return String.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
JSONObject json = new JSONObject();
json.put("answer",cellData.getStringValue());
return json.toString();
}
@Override
public CellData convertToExcelData(String value, ExcelContentProperty contentProperty,
GlobalConfiguration globalConfiguration) {
return new CellData(value);
}
}