EasyPoi简单用法

                                                        easyPoi			

  
  
  1. <!--EasyPoi导入导出-->
  2. <dependency>
  3. <groupId>cn.afterturn </groupId>
  4. <artifactId>easypoi-base </artifactId>
  5. <version>3.0.3 </version>
  6. </dependency>
  7. <dependency>
  8. <groupId>cn.afterturn </groupId>
  9. <artifactId>easypoi-web </artifactId>
  10. <version>3.0.3 </version> </dependency>
  11. <dependency>
  12. <groupId>cn.afterturn </groupId>
  13. <artifactId>easypoi-annotation </artifactId>
  14. <version>3.0.3 </version>
  15. </dependency>
  16. <!-- 文件上传 -->
  17. <dependency>
  18. <groupId>commons-fileupload </groupId>
  19. <artifactId>commons-fileupload </artifactId>
  20. <version>1.3.1 </version>
  21. </dependency>

2.导入工具类(官网和百度都有)


  
  
  1. package com.zzf.finals.utiles;
  2. import cn.afterturn.easypoi. excel.ExcelExportUtil;
  3. import cn.afterturn.easypoi.excel.ExcelImportUtil;
  4. import cn.afterturn.easypoi.excel.entity.ExportParams;
  5. import cn.afterturn.easypoi.excel.entity.ImportParams;
  6. import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
  7. import org.apache.commons.lang3.StringUtils;
  8. import org.apache.poi.ss.usermodel.Workbook;
  9. import org.springframework.web.multipart.MultipartFile;
  10. import javax.servlet.http.HttpServletResponse;
  11. import java.io.File;
  12. import java.io.IOException;
  13. import java.net.URLEncoder;
  14. import java.util.List;
  15. import java.util.Map;
  16. import java.util.NoSuchElementException;
  17. public class ExcelUtiles {
  18. public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,
  19. String fileName, boolean isCreateHeader, HttpServletResponse response){
  20. ExportParams exportParams = new ExportParams(title, sheetName);
  21. exportParams.setCreateHeadRows(isCreateHeader);
  22. defaultExport(list, pojoClass, fileName, response, exportParams);
  23. }
  24. public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,
  25. HttpServletResponse response){
  26. defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
  27. }
  28. public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
  29. defaultExport(list, fileName, response);
  30. }
  31. private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName,
  32. HttpServletResponse response, ExportParams exportParams) {
  33. Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
  34. if (workbook != null); downLoadExcel(fileName, response, workbook);
  35. }
  36. private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
  37. try {
  38. response.setCharacterEncoding( "UTF-8");
  39. response.setHeader( "content-Type", "application/vnd.ms-excel");
  40. response.setHeader( "Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
  41. workbook.write(response.getOutputStream());
  42. } catch (IOException e) {
  43. //throw new NormalException(e.getMessage());
  44. }
  45. }
  46. private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
  47. Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
  48. if (workbook != null);
  49. downLoadExcel(fileName, response, workbook);
  50. }
  51. public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
  52. if (StringUtils.isBlank(filePath)){
  53. return null;
  54. }
  55. ImportParams params = new ImportParams();
  56. params.setTitleRows(titleRows);
  57. params.setHeadRows(headerRows);
  58. List<T> list = null;
  59. try {
  60. list = ExcelImportUtil.importExcel( new File(filePath), pojoClass, params);
  61. } catch (NoSuchElementException e){
  62. //throw new NormalException("模板不能为空");
  63. } catch (Exception e) {
  64. e.printStackTrace();
  65. //throw new NormalException(e.getMessage());
  66. } return list;
  67. }
  68. public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
  69. if (file == null){ return null;
  70. }
  71. ImportParams params = new ImportParams();
  72. params.setTitleRows(titleRows);
  73. params.setHeadRows(headerRows);
  74. List<T> list = null;
  75. try {
  76. list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
  77. } catch (NoSuchElementException e){
  78. // throw new NormalException("excel文件不能为空");
  79. } catch (Exception e) {
  80. //throw new NormalException(e.getMessage());
  81. System.out.println(e.getMessage());
  82. }
  83. return list;
  84. }
  85. }

3.编写实体映射类


  
  
  1. package com.zzf.finals.entity;
  2. import cn.afterturn.easypoi.excel.annotation.Excel;
  3. import lombok.Data;
  4. import org.springframework.format.annotation.DateTimeFormat;
  5. import javax.persistence.*;
  6. import java.util.Date;
  7. @Entity
  8. @Table(name = "seckill")
  9. public class DemoExcel {
  10. @Id
  11. @GeneratedValue(strategy = GenerationType.IDENTITY)
  12. @Excel(name = "id" ,orderNum = "0")
  13. private Long seckillId;
  14. @Column(name = "name")
  15. @Excel(name = "姓名" ,orderNum = "1")
  16. private String name;
  17. @Column(name = "number")
  18. @Excel(name = "数量" ,orderNum = "2")
  19. private int number;
  20. @Column(name = "start_time")
  21. @Excel(name = "开始日期" ,orderNum = "3",importFormat = "yyyy-MM-dd HH:mm:ss") //exportFormat = "yyyy-MM-dd HH:mm:ss")
  22. private Date startTime;
  23. @Column(name = "end_time")
  24. @Excel(name = "结束日期" ,orderNum = "4",importFormat = "yyyy-MM-dd HH:mm:ss") //exportFormat = "yyyy-MM-dd HH:mm:ss")
  25. private Date endTime;
  26. @Column(name = "create_time")
  27. @Excel(name = "创建日期" ,orderNum = "5",importFormat = "yyyy-MM-dd HH:mm:ss") //exportFormat = "yyyy-MM-dd HH:mm:ss")
  28. private Date createTime;
  29. public Long getSeckillId() {
  30. return seckillId;
  31. }
  32. public void setSeckillId(Long seckillId) {
  33. this.seckillId = seckillId;
  34. }
  35. public String getName() {
  36. return name;
  37. }
  38. public void setName(String name) {
  39. this.name = name;
  40. }
  41. public int getNumber() {
  42. return number;
  43. }
  44. public void setNumber(int number) {
  45. this.number = number;
  46. }
  47. public Date getStartTime() {
  48. return startTime;
  49. }
  50. public void setStartTime(Date startTime) {
  51. this.startTime = startTime;
  52. }
  53. public Date getEndTime() {
  54. return endTime;
  55. }
  56. public void setEndTime(Date endTime) {
  57. this.endTime = endTime;
  58. }
  59. public Date getCreateTime() {
  60. return createTime;
  61. }
  62. public void setCreateTime(Date createTime) {
  63. this.createTime = createTime;
  64. }
  65. @Override
  66. public String toString() {
  67. return "DemoExcel{" +
  68. "seckillId=" + seckillId +
  69. ", name='" + name + '\'' +
  70. ", number=" + number +
  71. ", startTime=" + startTime +
  72. ", endTime=" + endTime +
  73. ", createTime=" + createTime +
  74. '}';
  75. }
  76. }

4.控制器代码


  
  
  1. package com.zzf.finals.controller;
  2. import cn.afterturn.easypoi.excel.ExcelImportUtil;
  3. import cn.afterturn.easypoi.excel.entity.ImportParams;
  4. import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
  5. import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
  6. import cn.afterturn.easypoi.util.PoiPublicUtil;
  7. import com.zzf.finals.entity.DemoExcel;
  8. import com.zzf.finals.repository.DemoExcelRepository;
  9. import com.zzf.finals.service.DemoService;
  10. import com.zzf.finals.utiles.ExcelUtiles;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.web.bind.annotation.*;
  13. import org.springframework.web.multipart.MultipartFile;
  14. import javax.servlet.http.HttpServletResponse;
  15. import java.io.File;
  16. import java.io.IOException;
  17. import java.text.SimpleDateFormat;
  18. import java.util.List;
  19. import java.util.Map;
  20. @RestController
  21. @RequestMapping( "/Excel")
  22. public class ExcelController {
  23. @Autowired
  24. private DemoExcelRepository demoExcelRepository;
  25. @Autowired
  26. private DemoService demoService;
  27. @GetMapping( "/export")
  28. public void export(HttpServletResponse response) {
  29. System.out.println( 1);
  30. // 模拟从数据库获取需要导出的数据
  31. List<DemoExcel> personList = demoExcelRepository.findAll();
  32. // 导出操作
  33. ExcelUtiles.exportExcel(personList, "测试名", "什么名字", DemoExcel.class, "测试.xls", response);
  34. }
  35. @PostMapping( "/importExcel2")
  36. public void importExcel2(@RequestParam("file") MultipartFile file) {
  37. ImportParams importParams = new ImportParams();
  38. // 数据处理
  39. importParams.setHeadRows( 1);
  40. importParams.setTitleRows( 1);
  41. // 需要验证
  42. importParams.setNeedVerfiy( true);
  43. try {
  44. ExcelImportResult<DemoExcel> result = ExcelImportUtil.importExcelMore(file.getInputStream(), DemoExcel.class,
  45. importParams);
  46. List<DemoExcel> successList = result.getList();
  47. for (DemoExcel demoExcel : successList) {
  48. System.out.println(demoExcel);
  49. }
  50. } catch (IOException e) {
  51. } catch (Exception e) {
  52. }
  53. }
  54. }

输入连接后如图所示。

导入后如:

最最最简单的导入导出就这么完成了。

修改自定义样式:

查看源码我发现他内部封装的是:

所以我们只需要设置这个样式就行了如:


  
  
  1. public class ShelterIExcelExportStyler extends ExcelExportStylerDefaultImpl implements IExcelExportStyler{
  2. public ShelterIExcelExportStyler(Workbook workbook) {
  3. super(workbook);
  4. }
  5. @Override
  6. public CellStyle getTitleStyle(short color) {
  7. CellStyle titleStyle = workbook.createCellStyle();
  8. titleStyle.setAlignment(CellStyle.ALIGN_CENTER);
  9. titleStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
  10. titleStyle.setWrapText( true);
  11. return titleStyle;
  12. }
  13. @Override
  14. public CellStyle stringSeptailStyle(Workbook workbook, boolean isWarp) {
  15. CellStyle style = workbook.createCellStyle();
  16. style.setAlignment(CellStyle.ALIGN_CENTER);
  17. style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
  18. style.setDataFormat(STRING_FORMAT);
  19. if (isWarp) {
  20. style.setWrapText( true);
  21. }
  22. return style;
  23. }
  24. @Override
  25. public CellStyle getHeaderStyle(short color) {
  26. CellStyle titleStyle = workbook.createCellStyle();
  27. Font font = workbook.createFont();
  28. font.setFontHeightInPoints(( short) 20);
  29. titleStyle.setFont(font);
  30. titleStyle.setAlignment(CellStyle.ALIGN_CENTER);
  31. titleStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
  32. return titleStyle;
  33. }
  34. @Override
  35. public CellStyle stringNoneStyle(Workbook workbook, boolean isWarp) {
  36. CellStyle style = workbook.createCellStyle();
  37. Font font = workbook.createFont();
  38. // font.setFontHeightInPoints((short) 15);
  39. style.setFont(font);
  40. style.setAlignment(CellStyle.ALIGN_CENTER);
  41. style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
  42. style.setDataFormat(STRING_FORMAT);
  43. if (isWarp) {
  44. style.setWrapText( true);
  45. }
  46. return style;
  47. }
  48. }

这里我只是简单的修改了他默认字体大小。如果要设置表格的宽度不可以在这里设置。


  
  
  1. private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName,
  2. HttpServletResponse response, ExportParams exportParams, String sheetName) {
  3. Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
  4. Sheet sheet=workbook.getSheet(sheetName);
  5. // sheet.CreateRow(0).Height = (short)(200*20);
  6. // sheet.createRow(0);
  7. sheet.getRow( 0).setHeight(( short)( 50* 20));
  8. sheet.getRow( 1).setHeight(( short)( 30* 20));
  9. if (workbook != null); downLoadExcel(fileName, response, workbook);
  10. }

他会调用ExportExcel返回一个Workbook对象,然后通过这个对象获取Sheet才能改变行的宽度千万不腰用CreateRow会覆盖。

有些人会在使用导入的时候出现只导入一条数据或者列缺少的情况,个人推荐可以使用步进指令去调试这段代码改成适用自己的”轮子“。我通过调试发现保存数据是这个方法:


  
  
  1. private <T> List<T> importExcel(Collection<T> result, Sheet sheet, Class<?> pojoClass, ImportParams params,
  2. Map<String, PictureData> pictures) throws Exception {
  3. List collection = new ArrayList();
  4. Map<String, ExcelImportEntity> excelParams = new HashMap<String, ExcelImportEntity>();
  5. List<ExcelCollectionParams> excelCollection = new ArrayList<ExcelCollectionParams>();
  6. String targetId = null;
  7. if (!Map.class. equals(pojoClass)) {
  8. Field[] fileds = PoiPublicUtil.getClassFields(pojoClass);
  9. ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class);
  10. if (etarget != null) {
  11. targetId = etarget. value();
  12. }
  13. getAllExcelField(targetId, fileds, excelParams, excelCollection, pojoClass, null, null);
  14. }
  15. Iterator<Row> rows = sheet.rowIterator();
  16. for ( int j = 0; j < params.getTitleRows(); j++) {
  17. rows.next();
  18. }
  19. Map<Integer, String> titlemap = getTitleMap(rows, params, excelCollection);
  20. checkIsValidTemplate(titlemap, excelParams, params, excelCollection);
  21. Row row = null;
  22. Object object = null;
  23. String picId;
  24. int readRow = 0;
  25. // 跳过无效行
  26. for ( int i = 0; i < params.getStartRows(); i++) {
  27. rows.next();
  28. }
  29. while (rows.hasNext()
  30. && (row == null || sheet.getLastRowNum() - row.getRowNum() > params.getLastOfInvalidRow())) {
  31. if ( params.getReadRows() > 0 && readRow > params.getReadRows()) {
  32. break;
  33. }
  34. row = rows.next();
  35. // Fix 如果row为无效行时候跳出
  36. if (sheet.getLastRowNum() - row.getRowNum() < params.getLastOfInvalidRow()) {
  37. break;
  38. }
  39. // 判断是集合元素还是不是集合元素,如果是就继续加入这个集合,不是就创建新的对象
  40. // keyIndex 如果为空就不处理,仍然处理这一行
  41. if ( params.getKeyIndex() != null && !(row.getCell( params.getKeyIndex()) == null
  42. || StringUtils.isEmpty(getKeyValue(row.getCell( params.getKeyIndex())))) && object != null) {
  43. for (ExcelCollectionParams param : excelCollection) {
  44. addListContinue( object, param, row, titlemap, targetId, pictures, params);
  45. }
  46. } else {
  47. object = PoiPublicUtil.createObject(pojoClass, targetId);
  48. try {
  49. // 标记为null的次数
  50. int count = 0;
  51. int sum = titlemap.size();
  52. for ( int i = row.getFirstCellNum(); i <= sum; i++) {
  53. Cell cell = row.getCell(i);
  54. boolean flag = true;
  55. if (cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) {
  56. count++;
  57. flag = false;
  58. }
  59. String titleString = (String) titlemap. get(i);
  60. if (excelParams.containsKey(titleString) || Map.class. equals(pojoClass)) {
  61. if (excelParams. get(titleString) != null && excelParams. get(titleString).getType() == 2) {
  62. picId = row.getRowNum() + "_" + i;
  63. saveImage( object, picId, excelParams, titleString, pictures, params);
  64. } else {
  65. if (saveFieldValue( params, object, cell, excelParams, titleString, row)) {
  66. if (flag) //只有当没有count++过才能添加。
  67. count++;
  68. }
  69. }
  70. }
  71. }
  72. for (ExcelCollectionParams param : excelCollection) {
  73. addListContinue( object, param, row, titlemap, targetId, pictures, params);
  74. }
  75. if (verifyingDataValidity( object, row, params, pojoClass)) {
  76. // count等于0或者
  77. if ((count == 0) || (count <= sum - 2))
  78. collection. add( object);
  79. } else {
  80. // 如果为null的次数小于5则添加
  81. // if (count!=0 || count < sum-3)
  82. failCollection. add( object);
  83. }
  84. } catch (ExcelImportException e) {
  85. LOGGER.error( "excel import error , row num:{},obj:{}", readRow,
  86. ReflectionToStringBuilder.toString( object));
  87. if (!e.getType(). equals(ExcelImportEnum.VERIFY_ERROR)) {
  88. throw new ExcelImportException(e.getType(), e);
  89. }
  90. } catch (Exception e) {
  91. LOGGER.error( "excel import error , row num:{},obj:{}", readRow,
  92. ReflectionToStringBuilder.toString( object));
  93. throw new RuntimeException(e);
  94. }
  95. }
  96. readRow++;
  97. }
  98. return collection;
  99. }

这个类是

修改的位置在这里,我通过修改这段代码使其强制进入else中可以拿到所有数据,然后判断null的次数选择是否添加。

适用自己的轮子才是最好的轮子……

文档地址:http://easypoi.mydoc.io/

参考:https://www.jianshu.com/p/5d67fb720ece

猜你喜欢

转载自blog.csdn.net/weixin_43710551/article/details/88735160