当前位置:   article > 正文

若依框架自定义导出Excel多sheet页+合并单元格(Poi)_若依导出excel合并单元格

若依导出excel合并单元格

先看效果:

 

 

在用若依框架是发现自带的导出功能中并不能导出多个sheet和合并单元格,所以我在这里做了修改希望可以帮到你,用到的点个赞呗!

我们先一步步来

整个程序的思路为先返回下载地址,然后根据下载地址去下载excel

一  : 返回下载地址

首先是我们需要excel的下载地址,这里我们直接跳到exportExcel方法,以下是代码部分

其中list,listyw为两个sheet页的数据

  1. @GetMapping("/export")
  2. public AjaxResult export(BizGuideFileDto bizGuideFile) {
  3. List<BizGuideFileDto> list=iBizGuideFileService.selectBizGuideFile(bizGuideFile);
  4. List<BizGuideFileDto> listyw=iBizGuideFileService.selectBizGuideFile2(bizGuideFile); ExcelUtilMerge<BizGuideFileDto> bizDSubjectExcelUtil = new ExcelUtilMerge<BizGuideFileDto>(BizGuideFileDto.class);
  5. return AjaxResult.success(bizDSubjectExcelUtil.exportExcel
  6. (list,listyw, "sheet1","sheet2","标题据",list.get(0).getFileTitle()));
  7. }
  8. public AjaxResult exportExcel(List<T> list,List<T> listyw, String sheetName,String sheetName2, String title,String title2)
  9. {
  10. this.init(list,listyw, sheetName,sheetName2, title, title2,Type.EXPORT, Excelyw.Type.EXPORT);
  11. return exportExcel();
  12. }

1、怎么建立多个sheet页

下面有我附上的工具类可以看到在方法init里面和源码相比多了几条尾号为2的,就是第二个sheet,在建工作簿、获取注解时、获取数据导出时都有相关的2,具体情况可以看代码/

具体逻辑可以从init里面一步步往下看

2、如何合并单元格

exportExcel() --->   
writeSheet() --->  
fillExcelData(index, row) --->
this.addCell(excel, row, vo, field, column++);
先根据这个思路看ExcelUtil<T>

合并的只有三行代码,这里我做了一个判断,因为在这个方法外面是一个for循环,不做判断的话回报多重合并的错误,虽然结果是对的,但是有强迫症的我看着不舒服

这里合并的逻辑为从第三行开始,第listyw.size()+1行结束,第0列开始,第0列结束

  1. if (heBing==true){
  2. CellRangeAddress region = new CellRangeAddress(2, (short)listyw.size()+1, 0, (short)0);
  3. sheet2.addMergedRegion(region);
  4. this.heBing=false;
  5. }

3、自定义导出字段

因为若依导出是可以自定义的选择导出的字段的,所以只需要给需要导出的字段加上注解就可以,@Excel为若依源码的,是获取第一个sheet的导出字段,@Excelyw是我自己加的获取另一个sheet页导出字段的注解,具体逻辑可以复制Excel的

@Excel:

  1. package com.gyjn.common.annotation;
  2. import com.gyjn.common.utils.poi.ExcelHandlerAdapter;
  3. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  4. import org.apache.poi.ss.usermodel.IndexedColors;
  5. import java.lang.annotation.ElementType;
  6. import java.lang.annotation.Retention;
  7. import java.lang.annotation.RetentionPolicy;
  8. import java.lang.annotation.Target;
  9. import java.math.BigDecimal;
  10. /**
  11. * 自定义导出Excel数据注解
  12. *
  13. * @author ruoyi
  14. */
  15. @Retention(RetentionPolicy.RUNTIME)
  16. @Target(ElementType.FIELD)
  17. public @interface Excel
  18. {
  19. /**
  20. * 导出时在excel中排序
  21. */
  22. public int sort() default Integer.MAX_VALUE;
  23. /**
  24. * 导出到Excel中的名字.
  25. */
  26. public String name() default "";
  27. /**
  28. * 日期格式, 如: yyyy-MM-dd
  29. */
  30. public String dateFormat() default "";
  31. /**
  32. * 如果是字典类型,请设置字典的type值 (如: sys_user_sex)
  33. */
  34. public String dictType() default "";
  35. /**
  36. * 读取内容转表达式 (如: 0=男,1=女,2=未知)
  37. */
  38. public String readConverterExp() default "";
  39. /**
  40. * 分隔符,读取字符串组内容
  41. */
  42. public String separator() default ",";
  43. /**
  44. * BigDecimal 精度 默认:-1(默认不开启BigDecimal格式化)
  45. */
  46. public int scale() default -1;
  47. /**
  48. * BigDecimal 舍入规则 默认:BigDecimal.ROUND_HALF_EVEN
  49. */
  50. public int roundingMode() default BigDecimal.ROUND_HALF_EVEN;
  51. /**
  52. * 导出时在excel中每个列的高度 单位为字符
  53. */
  54. public double height() default 14;
  55. /**
  56. * 导出时在excel中每个列的宽 单位为字符
  57. */
  58. public double width() default 16;
  59. /**
  60. * 文字后缀,如% 90 变成90%
  61. */
  62. public String suffix() default "";
  63. /**
  64. * 当值为空时,字段的默认值
  65. */
  66. public String defaultValue() default "";
  67. /**
  68. * 提示信息
  69. */
  70. public String prompt() default "";
  71. /**
  72. * 设置只能选择不能输入的列内容.
  73. */
  74. public String[] combo() default {};
  75. /**
  76. * 是否导出数据,应对需求:有时我们需要导出一份模板,这是标题需要但内容需要用户手工填写.
  77. */
  78. public boolean isExport() default true;
  79. /**
  80. * 另一个类中的属性名称,支持多级获取,以小数点隔开
  81. */
  82. public String targetAttr() default "";
  83. public String mergeLine() default "";
  84. /**
  85. * 是否自动统计数据,在最后追加一行统计数据总和
  86. */
  87. public boolean isStatistics() default false;
  88. /**
  89. * 导出类型(0数字 1字符串)
  90. */
  91. public ColumnType cellType() default ColumnType.STRING;
  92. /**
  93. * 导出字体颜色
  94. */
  95. public IndexedColors color() default IndexedColors.BLACK;
  96. /**
  97. * 导出字段对齐方式
  98. */
  99. public HorizontalAlignment align() default HorizontalAlignment.CENTER;
  100. /**
  101. * 自定义数据处理器
  102. */
  103. public Class<?> handler() default ExcelHandlerAdapter.class;
  104. /**
  105. * 自定义数据处理器参数
  106. */
  107. public String[] args() default {};
  108. public enum Align
  109. {
  110. AUTO(0), LEFT(1), CENTER(2), RIGHT(3);
  111. private final int value;
  112. Align(int value)
  113. {
  114. this.value = value;
  115. }
  116. public int value()
  117. {
  118. return this.value;
  119. }
  120. }
  121. /**
  122. * 字段类型(0:导出导入;1:仅导出;2:仅导入)
  123. */
  124. Type type() default Type.ALL;
  125. public enum Type
  126. {
  127. ALL(0), EXPORT(1), IMPORT(2);
  128. private final int value;
  129. Type(int value)
  130. {
  131. this.value = value;
  132. }
  133. public int value()
  134. {
  135. return this.value;
  136. }
  137. }
  138. public enum ColumnType
  139. {
  140. NUMERIC(0), STRING(1), IMAGE(2);
  141. private final int value;
  142. ColumnType(int value)
  143. {
  144. this.value = value;
  145. }
  146. public int value()
  147. {
  148. return this.value;
  149. }
  150. }
  151. }

@Excelyw

  1. package com.gyjn.common.annotation;
  2. import com.gyjn.common.utils.poi.ExcelHandlerAdapter;
  3. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  4. import org.apache.poi.ss.usermodel.IndexedColors;
  5. import java.lang.annotation.ElementType;
  6. import java.lang.annotation.Retention;
  7. import java.lang.annotation.RetentionPolicy;
  8. import java.lang.annotation.Target;
  9. import java.math.BigDecimal;
  10. /**
  11. * 自定义导出Excel数据注解
  12. *
  13. * @author ruoyi
  14. */
  15. @Retention(RetentionPolicy.RUNTIME)
  16. @Target(ElementType.FIELD)
  17. public @interface Excelyw
  18. {
  19. /**
  20. * 导出时在excel中排序
  21. */
  22. public int sort() default Integer.MAX_VALUE;
  23. /**
  24. * 导出到Excel中的名字.
  25. */
  26. public String name() default "";
  27. /**
  28. * 日期格式, 如: yyyy-MM-dd
  29. */
  30. public String dateFormat() default "";
  31. /**
  32. * 如果是字典类型,请设置字典的type值 (如: sys_user_sex)
  33. */
  34. public String dictType() default "";
  35. /**
  36. * 读取内容转表达式 (如: 0=男,1=女,2=未知)
  37. */
  38. public String readConverterExp() default "";
  39. /**
  40. * 分隔符,读取字符串组内容
  41. */
  42. public String separator() default ",";
  43. /**
  44. * BigDecimal 精度 默认:-1(默认不开启BigDecimal格式化)
  45. */
  46. public int scale() default -1;
  47. /**
  48. * BigDecimal 舍入规则 默认:BigDecimal.ROUND_HALF_EVEN
  49. */
  50. public int roundingMode() default BigDecimal.ROUND_HALF_EVEN;
  51. /**
  52. * 导出时在excel中每个列的高度 单位为字符
  53. */
  54. public double height() default 14;
  55. /**
  56. * 导出时在excel中每个列的宽 单位为字符
  57. */
  58. public double width() default 16;
  59. /**
  60. * 文字后缀,如% 90 变成90%
  61. */
  62. public String suffix() default "";
  63. /**
  64. * 当值为空时,字段的默认值
  65. */
  66. public String defaultValue() default "";
  67. /**
  68. * 提示信息
  69. */
  70. public String prompt() default "";
  71. /**
  72. * 设置只能选择不能输入的列内容.
  73. */
  74. public String[] combo() default {};
  75. /**
  76. * 是否导出数据,应对需求:有时我们需要导出一份模板,这是标题需要但内容需要用户手工填写.
  77. */
  78. public boolean isExport() default true;
  79. /**
  80. * 另一个类中的属性名称,支持多级获取,以小数点隔开
  81. */
  82. public String targetAttr() default "";
  83. public String mergeLine() default "";
  84. /**
  85. * 是否自动统计数据,在最后追加一行统计数据总和
  86. */
  87. public boolean isStatistics() default false;
  88. /**
  89. * 导出类型(0数字 1字符串)
  90. */
  91. public ColumnType cellType() default ColumnType.STRING;
  92. /**
  93. * 导出字体颜色
  94. */
  95. public IndexedColors color() default IndexedColors.BLACK;
  96. /**
  97. * 导出字段对齐方式
  98. */
  99. public HorizontalAlignment align() default HorizontalAlignment.CENTER;
  100. /**
  101. * 自定义数据处理器
  102. */
  103. public Class<?> handler() default ExcelHandlerAdapter.class;
  104. /**
  105. * 自定义数据处理器参数
  106. */
  107. public String[] args() default {};
  108. public enum Align
  109. {
  110. AUTO(0), LEFT(1), CENTER(2), RIGHT(3);
  111. private final int value;
  112. Align(int value)
  113. {
  114. this.value = value;
  115. }
  116. public int value()
  117. {
  118. return this.value;
  119. }
  120. }
  121. /**
  122. * 字段类型(0:导出导入;1:仅导出;2:仅导入)
  123. */
  124. Type type() default Type.ALL;
  125. public enum Type
  126. {
  127. ALL(0), EXPORT(1), IMPORT(2);
  128. private final int value;
  129. Type(int value)
  130. {
  131. this.value = value;
  132. }
  133. public int value()
  134. {
  135. return this.value;
  136. }
  137. }
  138. public enum ColumnType
  139. {
  140. NUMERIC(0), STRING(1), IMAGE(2);
  141. private final int value;
  142. ColumnType(int value)
  143. {
  144. this.value = value;
  145. }
  146. public int value()
  147. {
  148. return this.value;
  149. }
  150. }
  151. }

二 :根据下载地址下载excel

  1. @GetMapping("/download")
  2. public void fileDownload(String fileName, String excelName, HttpServletResponse response, HttpServletRequest request) {
  3. try {
  4. if (!FileUtils.checkAllowDownload(fileName)) {
  5. throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
  6. }
  7. String realFileName = excelName + fileName.substring(fileName.indexOf("_"));
  8. String filePath = RuoYiConfig.getDownloadPath() + fileName;
  9. response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
  10. // 下载文件名重新编码
  11. FileUtils.setAttachmentResponseHeader(response, realFileName);
  12. FileUtils.writeBytes(filePath, response.getOutputStream());
  13. } catch (Exception e) {
  14. e.printStackTrace();
  15. }
  16. }

最后

给你附上exportExcel所在的工具类,具体看相关代码,整个工具类复制就可以用了

  1. import com.gyjn.common.annotation.Excel;
  2. import com.gyjn.common.annotation.Excel.ColumnType;
  3. import com.gyjn.common.annotation.Excel.Type;
  4. import com.gyjn.common.annotation.Excels;
  5. import com.gyjn.common.annotation.Excelyw;
  6. import com.gyjn.common.annotation.Excelyws;
  7. import com.gyjn.common.config.RuoYiConfig;
  8. import com.gyjn.common.core.domain.AjaxResult;
  9. import com.gyjn.common.core.text.Convert;
  10. import com.gyjn.common.exception.UtilException;
  11. import com.gyjn.common.utils.DateUtils;
  12. import com.gyjn.common.utils.DictUtils;
  13. import com.gyjn.common.utils.StringUtils;
  14. import com.gyjn.common.utils.file.FileTypeUtils;
  15. import com.gyjn.common.utils.file.FileUtils;
  16. import com.gyjn.common.utils.file.ImageUtils;
  17. import com.gyjn.common.utils.reflect.ReflectUtils;
  18. import org.apache.commons.lang3.RegExUtils;
  19. import org.apache.poi.hssf.usermodel.*;
  20. import org.apache.poi.ooxml.POIXMLDocumentPart;
  21. import org.apache.poi.ss.usermodel.*;
  22. import org.apache.poi.ss.util.CellRangeAddress;
  23. import org.apache.poi.ss.util.CellRangeAddressList;
  24. import org.apache.poi.util.IOUtils;
  25. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  26. import org.apache.poi.xssf.usermodel.*;
  27. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
  28. import org.slf4j.Logger;
  29. import org.slf4j.LoggerFactory;
  30. import javax.servlet.http.HttpServletResponse;
  31. import java.io.*;
  32. import java.lang.reflect.Field;
  33. import java.lang.reflect.Method;
  34. import java.math.BigDecimal;
  35. import java.text.DecimalFormat;
  36. import java.time.LocalDate;
  37. import java.time.LocalDateTime;
  38. import java.util.*;
  39. import java.util.stream.Collectors;
  40. /**
  41. * Excel相关处理
  42. *
  43. * @author cyf
  44. */
  45. public class ExcelUtil<T>
  46. {
  47. private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
  48. public static final String FORMULA_REGEX_STR = "=|-|\\+|@";
  49. public static final String[] FORMULA_STR = { "=", "-", "+", "@" };
  50. /**
  51. * Excel sheet最大行数,默认65536
  52. */
  53. public static final int sheetSize = 65536;
  54. /**
  55. * 工作表名称
  56. */
  57. private String sheetName;
  58. private String sheetName2;
  59. /**
  60. * 导出类型(EXPORT:导出数据;IMPORT:导入模板)
  61. */
  62. private Type type;
  63. private Excelyw.Type type2;
  64. /**
  65. * 工作薄对象
  66. */
  67. private Workbook wb;
  68. private Workbook wb2;
  69. /**
  70. * 工作表对象
  71. */
  72. private Sheet sheet;
  73. private Sheet sheet2;
  74. /**
  75. * 样式列表
  76. */
  77. private Map<String, CellStyle> styles;
  78. private Map<String, CellStyle> styles2;
  79. /**
  80. * 导入导出数据列表
  81. */
  82. private List<T> list;
  83. private List<T> listyw;
  84. /**
  85. * 注解列表
  86. */
  87. private List<Object[]> fields;
  88. private List<Object[]> fields2;
  89. /**
  90. * 当前行号
  91. */
  92. private int rownum;
  93. /**
  94. * 标题
  95. */
  96. private String title;
  97. private String title2;
  98. /**
  99. * 最大高度
  100. */
  101. private short maxHeight;
  102. private short maxHeight2;
  103. /**
  104. * 统计列表
  105. */
  106. private Map<Integer, Double> statistics = new HashMap<Integer, Double>();
  107. private Map<Integer, Double> statistics2 = new HashMap<Integer, Double>();
  108. /**
  109. * 数字格式
  110. */
  111. private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
  112. /**
  113. * 实体对象
  114. */
  115. public Class<T> clazz;
  116. private boolean heBing=true;
  117. public ExcelUtilMerge(Class<T> clazz)
  118. {
  119. this.clazz = clazz;
  120. }
  121. public void init(List<T> list,List<T> listyw, String sheetName, String sheetName2, String title, String title2, Type type, Excelyw.Type type2)
  122. {
  123. if (list == null)
  124. {
  125. list = new ArrayList<T>();
  126. }
  127. this.list = list;
  128. this.listyw = listyw;
  129. this.sheetName = sheetName;
  130. this.sheetName2 = sheetName2;
  131. this.type = type;
  132. this.type2 = type2;
  133. this.title = title;
  134. this.title2 = title2;
  135. createExcelField();
  136. createExcelField2();
  137. createWorkbook();
  138. createTitle();
  139. createTitle2();
  140. }
  141. /**
  142. * 创建excel第一行标题
  143. */
  144. public void createTitle()
  145. {
  146. if (StringUtils.isNotEmpty(title))
  147. {
  148. Row titleRow = sheet.createRow(rownum == 0 ? rownum++ : 0);
  149. titleRow.setHeightInPoints(30);
  150. Cell titleCell = titleRow.createCell(0);
  151. titleCell.setCellStyle(styles.get("title"));
  152. titleCell.setCellValue(title);
  153. sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(),
  154. this.fields.size() - 1));
  155. }
  156. }
  157. public void createTitle2()
  158. {
  159. if (StringUtils.isNotEmpty(title2))
  160. {
  161. Row titleRow = sheet2.createRow(rownum == 0 ? rownum++ : 0);
  162. titleRow.setHeightInPoints(30);
  163. Cell titleCell = titleRow.createCell(0);
  164. titleCell.setCellStyle(styles2.get("title"));
  165. titleCell.setCellValue(title2);
  166. sheet2.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(),
  167. this.fields2.size() - 1));
  168. }
  169. }
  170. /**
  171. * 对excel表单默认第一个索引名转换成list
  172. *
  173. * @param is 输入流
  174. * @return 转换后集合
  175. */
  176. public List<T> importExcel(InputStream is) throws Exception
  177. {
  178. return importExcel(is, 0);
  179. }
  180. /**
  181. * 对excel表单默认第一个索引名转换成list
  182. *
  183. * @param is 输入流
  184. * @param titleNum 标题占用行数
  185. * @return 转换后集合
  186. */
  187. public List<T> importExcel(InputStream is, int titleNum) throws Exception
  188. {
  189. return importExcel(StringUtils.EMPTY, is, titleNum);
  190. }
  191. /**
  192. * 对excel表单指定表格索引名转换成list
  193. *
  194. * @param sheetName 表格索引名
  195. * @param titleNum 标题占用行数
  196. * @param is 输入流
  197. * @return 转换后集合
  198. */
  199. public List<T> importExcel(String sheetName, InputStream is, int titleNum) throws Exception
  200. {
  201. this.type = Type.IMPORT;
  202. this.wb = WorkbookFactory.create(is);
  203. List<T> list = new ArrayList<T>();
  204. // 如果指定sheet名,则取指定sheet中的内容 否则默认指向第1个sheet
  205. Sheet sheet = StringUtils.isNotEmpty(sheetName) ? wb.getSheet(sheetName) : wb.getSheetAt(0);
  206. if (sheet == null)
  207. {
  208. throw new IOException("文件sheet不存在");
  209. }
  210. boolean isXSSFWorkbook = !(wb instanceof HSSFWorkbook);
  211. Map<String, PictureData> pictures;
  212. if (isXSSFWorkbook)
  213. {
  214. pictures = getSheetPictures07((XSSFSheet) sheet, (XSSFWorkbook) wb);
  215. }
  216. else
  217. {
  218. pictures = getSheetPictures03((HSSFSheet) sheet, (HSSFWorkbook) wb);
  219. }
  220. // 获取最后一个非空行的行下标,比如总行数为n,则返回的为n-1
  221. int rows = sheet.getLastRowNum();
  222. if (rows > 0)
  223. {
  224. // 定义一个map用于存放excel列的序号和field.
  225. Map<String, Integer> cellMap = new HashMap<String, Integer>();
  226. // 获取表头
  227. Row heard = sheet.getRow(titleNum);
  228. for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++)
  229. {
  230. Cell cell = heard.getCell(i);
  231. if (StringUtils.isNotNull(cell))
  232. {
  233. String value = this.getCellValue(heard, i).toString();
  234. cellMap.put(value, i);
  235. }
  236. else
  237. {
  238. cellMap.put(null, i);
  239. }
  240. }
  241. // 有数据时才处理 得到类的所有field.
  242. List<Object[]> fields = this.getFields();
  243. Map<Integer, Object[]> fieldsMap = new HashMap<Integer, Object[]>();
  244. for (Object[] objects : fields)
  245. {
  246. Excel attr = (Excel) objects[1];
  247. Integer column = cellMap.get(attr.name());
  248. if (column != null)
  249. {
  250. fieldsMap.put(column, objects);
  251. }
  252. }
  253. for (int i = titleNum + 1; i <= rows; i++)
  254. {
  255. // 从第2行开始取数据,默认第一行是表头.
  256. Row row = sheet.getRow(i);
  257. // 判断当前行是否是空行
  258. if (isRowEmpty(row))
  259. {
  260. continue;
  261. }
  262. T entity = null;
  263. for (Map.Entry<Integer, Object[]> entry : fieldsMap.entrySet())
  264. {
  265. Object val = this.getCellValue(row, entry.getKey());
  266. // 如果不存在实例则新建.
  267. entity = (entity == null ? clazz.newInstance() : entity);
  268. // 从map中得到对应列的field.
  269. Field field = (Field) entry.getValue()[0];
  270. Excel attr = (Excel) entry.getValue()[1];
  271. // 取得类型,并根据对象类型设置值.
  272. Class<?> fieldType = field.getType();
  273. if (String.class == fieldType)
  274. {
  275. String s = Convert.toStr(val);
  276. if (StringUtils.endsWith(s, ".0"))
  277. {
  278. val = StringUtils.substringBefore(s, ".0");
  279. }
  280. else
  281. {
  282. String dateFormat = field.getAnnotation(Excel.class).dateFormat();
  283. if (StringUtils.isNotEmpty(dateFormat))
  284. {
  285. val = parseDateToStr(dateFormat, val);
  286. }
  287. else
  288. {
  289. val = Convert.toStr(val);
  290. }
  291. }
  292. }
  293. else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
  294. {
  295. val = Convert.toInt(val);
  296. }
  297. else if ((Long.TYPE == fieldType || Long.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
  298. {
  299. val = Convert.toLong(val);
  300. }
  301. else if (Double.TYPE == fieldType || Double.class == fieldType)
  302. {
  303. val = Convert.toDouble(val);
  304. }
  305. else if (Float.TYPE == fieldType || Float.class == fieldType)
  306. {
  307. val = Convert.toFloat(val);
  308. }
  309. else if (BigDecimal.class == fieldType)
  310. {
  311. val = Convert.toBigDecimal(val);
  312. }
  313. else if (Date.class == fieldType)
  314. {
  315. if (val instanceof String)
  316. {
  317. val = DateUtils.parseDate(val);
  318. }
  319. else if (val instanceof Double)
  320. {
  321. val = DateUtil.getJavaDate((Double) val);
  322. }
  323. }
  324. else if (Boolean.TYPE == fieldType || Boolean.class == fieldType)
  325. {
  326. val = Convert.toBool(val, false);
  327. }
  328. if (StringUtils.isNotNull(fieldType))
  329. {
  330. String propertyName = field.getName();
  331. if (StringUtils.isNotEmpty(attr.targetAttr()))
  332. {
  333. propertyName = field.getName() + "." + attr.targetAttr();
  334. }
  335. else if (StringUtils.isNotEmpty(attr.readConverterExp()))
  336. {
  337. val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
  338. }
  339. else if (StringUtils.isNotEmpty(attr.dictType()))
  340. {
  341. val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
  342. }
  343. else if (!attr.handler().equals(ExcelHandlerAdapter.class))
  344. {
  345. val = dataFormatHandlerAdapter(val, attr);
  346. }
  347. else if (ColumnType.IMAGE == attr.cellType() && StringUtils.isNotEmpty(pictures))
  348. {
  349. PictureData image = pictures.get(row.getRowNum() + "_" + entry.getKey());
  350. if (image == null)
  351. {
  352. val = "";
  353. }
  354. else
  355. {
  356. byte[] data = image.getData();
  357. val = FileUtils.writeImportBytes(data);
  358. }
  359. }
  360. ReflectUtils.invokeSetter(entity, propertyName, val);
  361. }
  362. }
  363. list.add(entity);
  364. }
  365. }
  366. return list;
  367. }
  368. /**
  369. * 对list数据源将其里面的数据导入到excel表单
  370. *
  371. * @param list 导出数据集合
  372. * @param sheetName 工作表的名称
  373. * @return 结果
  374. */
  375. public AjaxResult exportExcel(List<T> list, String sheetName,String sheetName2)
  376. {
  377. return exportExcel(list, sheetName,sheetName2);
  378. }
  379. /**
  380. * 对list数据源将其里面的数据导入到excel表单
  381. *
  382. * @param list 导出数据集合
  383. * @param sheetName 工作表的名称
  384. * @param title 标题
  385. * @return 结果
  386. */
  387. public AjaxResult exportExcel(List<T> list,List<T> listyw, String sheetName,String sheetName2, String title,String title2)
  388. {
  389. this.init(list,listyw, sheetName,sheetName2, title, title2,Type.EXPORT, Excelyw.Type.EXPORT);
  390. return exportExcel();
  391. }
  392. /**
  393. * 对list数据源将其里面的数据导入到excel表单
  394. *
  395. * @param response 返回数据
  396. * @param list 导出数据集合
  397. * @param sheetName 工作表的名称
  398. * @return 结果
  399. */
  400. public void exportExcel(HttpServletResponse response, List<T> list, String sheetName,String sheetName2)
  401. {
  402. exportExcel(response, list, sheetName, sheetName2);
  403. }
  404. /**
  405. * 对list数据源将其里面的数据导入到excel表单
  406. *
  407. * @param response 返回数据
  408. * @param list 导出数据集合
  409. * @param sheetName 工作表的名称
  410. * @param title 标题
  411. * @return 结果
  412. */
  413. public void exportExcel(HttpServletResponse response,
  414. List<T> list, List<T> listyw,String sheetName,String sheetName2, String title, String title2)
  415. {
  416. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  417. response.setCharacterEncoding("utf-8");
  418. this.init(list,listyw, sheetName,sheetName2, title,title2, Type.EXPORT, Excelyw.Type.EXPORT);
  419. exportExcel(response);
  420. }
  421. /**
  422. * 对list数据源将其里面的数据导入到excel表单
  423. *
  424. * @param sheetName 工作表的名称
  425. * @return 结果
  426. */
  427. public AjaxResult importTemplateExcel(String sheetName,String sheetName2)
  428. {
  429. return importTemplateExcel(sheetName, sheetName2);
  430. }
  431. /**
  432. * 对list数据源将其里面的数据导入到excel表单
  433. *
  434. * @param sheetName 工作表的名称
  435. * @param title 标题
  436. * @return 结果
  437. */
  438. public AjaxResult importTemplateExcel(String sheetName, String sheetName2,String title)
  439. {
  440. this.init(null,null, sheetName,sheetName2, title,title2, Type.IMPORT, Excelyw.Type.EXPORT);
  441. return exportExcel();
  442. }
  443. /**
  444. * 对list数据源将其里面的数据导入到excel表单
  445. *
  446. * @param sheetName 工作表的名称
  447. * @return 结果
  448. */
  449. public void importTemplateExcel(HttpServletResponse response,
  450. String sheetName,String sheetName2)
  451. {
  452. importTemplateExcel(response, sheetName,sheetName2);
  453. }
  454. /**
  455. * 对list数据源将其里面的数据导入到excel表单
  456. *
  457. * @param sheetName 工作表的名称
  458. * @param title 标题
  459. * @return 结果
  460. */
  461. public void importTemplateExcel(HttpServletResponse response,
  462. String sheetName,String sheetName2, String title, String title2)
  463. {
  464. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  465. response.setCharacterEncoding("utf-8");
  466. this.init(null,null, sheetName, sheetName2,title,title2, Type.IMPORT, Excelyw.Type.EXPORT);
  467. exportExcel(response);
  468. }
  469. /**
  470. * 对list数据源将其里面的数据导入到excel表单
  471. *
  472. * @return 结果
  473. */
  474. public void exportExcel(HttpServletResponse response)
  475. {
  476. try
  477. {
  478. writeSheet();
  479. wb.write(response.getOutputStream());
  480. }
  481. catch (Exception e)
  482. {
  483. log.error("导出Excel异常{}", e.getMessage());
  484. }
  485. finally
  486. {
  487. IOUtils.closeQuietly(wb);
  488. }
  489. }
  490. /**
  491. * 对list数据源将其里面的数据导入到excel表单
  492. *
  493. * @return 结果
  494. */
  495. public AjaxResult exportExcel()
  496. {
  497. OutputStream out = null;
  498. try
  499. {
  500. writeSheet();
  501. String filename = encodingFilename(sheetName);
  502. out = new FileOutputStream(getAbsoluteFile(filename));
  503. wb.write(out);
  504. return AjaxResult.success(filename);
  505. }
  506. catch (Exception e)
  507. {
  508. log.error("导出Excel异常{}", e.getMessage());
  509. throw new UtilException("导出Excel失败,请联系网站管理员!");
  510. }
  511. finally
  512. {
  513. IOUtils.closeQuietly(wb);
  514. IOUtils.closeQuietly(out);
  515. }
  516. }
  517. /**
  518. * 创建写入数据到Sheet
  519. */
  520. public void writeSheet()
  521. {
  522. // 取出一共有多少个sheet.
  523. int sheetNo = Math.max(1, (int) Math.ceil(list.size() * 1.0 / sheetSize));
  524. for (int index = 0; index < sheetNo; index++)
  525. {
  526. createSheet(sheetNo, index);
  527. // 产生一行
  528. Row row = sheet.createRow(rownum);
  529. int column = 0;
  530. // 写入各个字段的列头名称
  531. for (Object[] os : fields)
  532. {
  533. Excel excel = (Excel) os[1];
  534. this.createCell(excel, row, column++);
  535. }
  536. if (Type.EXPORT.equals(type))
  537. {
  538. fillExcelData(index, row);
  539. addStatisticsRow();
  540. }
  541. }
  542. int sheetNo2 = Math.max(1, (int) Math.ceil(listyw.size() * 1.0 / sheetSize));
  543. for (int index = 0; index < sheetNo2; index++)
  544. {
  545. createSheet(sheetNo2, index);
  546. // 产生一行
  547. Row row2 = sheet2.createRow(rownum);
  548. int column = 0;
  549. // 写入各个字段的列头名称
  550. for (Object[] os : fields2)
  551. {
  552. Excelyw excel = (Excelyw) os[1];
  553. this.createCell2(excel, row2, column++);
  554. }
  555. if (Excelyw.Type.EXPORT.equals(type2))
  556. {
  557. fillExcelData2(index, row2);
  558. addStatisticsRow2();
  559. }
  560. }
  561. }
  562. /**
  563. * 填充excel数据
  564. *
  565. * @param index 序号
  566. * @param row 单元格行
  567. */
  568. public void fillExcelData(int index, Row row)
  569. {
  570. int startNo = index * sheetSize;
  571. int endNo = Math.min(startNo + sheetSize, list.size());
  572. for (int i = startNo; i < endNo; i++)
  573. {
  574. row = sheet.createRow(i + 1 + rownum - startNo);
  575. // 得到导出对象.
  576. T vo = (T) list.get(i);
  577. int column = 0;
  578. for (Object[] os : fields)
  579. {
  580. Field field = (Field) os[0];
  581. Excel excel = (Excel) os[1];
  582. this.addCell(excel, row, vo, field, column++);
  583. }
  584. }
  585. }
  586. public void fillExcelData2(int index, Row row2)
  587. {
  588. int startNo = index * sheetSize;
  589. int endNo = Math.min(startNo + sheetSize, listyw.size());
  590. for (int i = startNo; i < endNo; i++)
  591. {
  592. row2 = sheet2.createRow(i + 1 + rownum - startNo);
  593. // 得到导出对象.
  594. T vo = (T) listyw.get(i);
  595. int column = 0;
  596. for (Object[] os : fields2)
  597. {
  598. Field field = (Field) os[0];
  599. Excelyw excel = (Excelyw) os[1];
  600. this.addCell2(excel, row2, vo, field, column++);
  601. }
  602. }
  603. }
  604. /**
  605. * 创建表格样式
  606. *
  607. * @param wb 工作薄对象
  608. * @return 样式列表
  609. */
  610. private Map<String, CellStyle> createStyles(Workbook wb)
  611. {
  612. // 写入各条记录,每条记录对应excel表中的一行
  613. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  614. CellStyle style = wb.createCellStyle();
  615. style.setWrapText(true);
  616. style.setAlignment(HorizontalAlignment.CENTER);
  617. style.setVerticalAlignment(VerticalAlignment.CENTER);
  618. Font titleFont = wb.createFont();
  619. titleFont.setFontName("Arial");
  620. titleFont.setFontHeightInPoints((short) 16);
  621. titleFont.setBold(true);
  622. style.setFont(titleFont);
  623. styles.put("title", style);
  624. style = wb.createCellStyle();
  625. style.setWrapText(true);
  626. style.setAlignment(HorizontalAlignment.CENTER);
  627. style.setVerticalAlignment(VerticalAlignment.CENTER);
  628. style.setBorderRight(BorderStyle.THIN);
  629. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  630. style.setBorderLeft(BorderStyle.THIN);
  631. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  632. style.setBorderTop(BorderStyle.THIN);
  633. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  634. style.setBorderBottom(BorderStyle.THIN);
  635. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  636. Font dataFont = wb.createFont();
  637. dataFont.setFontName("Arial");
  638. dataFont.setFontHeightInPoints((short) 11);
  639. style.setFont(dataFont);
  640. styles.put("data", style);
  641. style = wb.createCellStyle();
  642. style.setWrapText(true);
  643. style.cloneStyleFrom(styles.get("data"));
  644. style.setAlignment(HorizontalAlignment.CENTER);
  645. style.setVerticalAlignment(VerticalAlignment.CENTER);
  646. style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
  647. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  648. Font headerFont = wb.createFont();
  649. headerFont.setFontName("Arial");
  650. headerFont.setFontHeightInPoints((short) 11);
  651. headerFont.setBold(true);
  652. headerFont.setColor(IndexedColors.BLACK.getIndex());
  653. style.setFont(headerFont);
  654. styles.put("header", style);
  655. style = wb.createCellStyle();
  656. style.setWrapText(true);
  657. style.setAlignment(HorizontalAlignment.CENTER);
  658. style.setVerticalAlignment(VerticalAlignment.CENTER);
  659. Font totalFont = wb.createFont();
  660. totalFont.setFontName("Arial");
  661. totalFont.setFontHeightInPoints((short) 11);
  662. style.setFont(totalFont);
  663. styles.put("total", style);
  664. styles.putAll(annotationStyles(wb));
  665. return styles;
  666. }
  667. private Map<String, CellStyle> createStyles2(Workbook wb)
  668. {
  669. // 写入各条记录,每条记录对应excel表中的一行
  670. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  671. CellStyle style = wb.createCellStyle();
  672. style.setWrapText(true);
  673. style.setAlignment(HorizontalAlignment.CENTER);
  674. style.setVerticalAlignment(VerticalAlignment.CENTER);
  675. Font titleFont = wb.createFont();
  676. titleFont.setFontName("Arial");
  677. titleFont.setFontHeightInPoints((short) 16);
  678. titleFont.setBold(true);
  679. style.setFont(titleFont);
  680. styles.put("title", style);
  681. style = wb.createCellStyle();
  682. style.setWrapText(true);
  683. style.setAlignment(HorizontalAlignment.CENTER);
  684. style.setVerticalAlignment(VerticalAlignment.CENTER);
  685. style.setBorderRight(BorderStyle.THIN);
  686. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  687. style.setBorderLeft(BorderStyle.THIN);
  688. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  689. style.setBorderTop(BorderStyle.THIN);
  690. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  691. style.setBorderBottom(BorderStyle.THIN);
  692. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  693. Font dataFont = wb.createFont();
  694. dataFont.setFontName("Arial");
  695. dataFont.setFontHeightInPoints((short) 11);
  696. style.setFont(dataFont);
  697. styles.put("data", style);
  698. style = wb.createCellStyle();
  699. style.setWrapText(true);
  700. style.cloneStyleFrom(styles.get("data"));
  701. style.setAlignment(HorizontalAlignment.CENTER);
  702. style.setVerticalAlignment(VerticalAlignment.CENTER);
  703. style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
  704. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  705. Font headerFont = wb.createFont();
  706. headerFont.setFontName("Arial");
  707. headerFont.setFontHeightInPoints((short) 11);
  708. headerFont.setBold(true);
  709. headerFont.setColor(IndexedColors.BLACK.getIndex());
  710. style.setFont(headerFont);
  711. styles.put("header", style);
  712. style = wb.createCellStyle();
  713. style.setWrapText(true);
  714. style.setAlignment(HorizontalAlignment.CENTER);
  715. style.setVerticalAlignment(VerticalAlignment.CENTER);
  716. Font totalFont = wb.createFont();
  717. totalFont.setFontName("Arial");
  718. totalFont.setFontHeightInPoints((short) 11);
  719. style.setFont(totalFont);
  720. styles.put("total", style);
  721. styles.putAll(annotationStyles2(wb));
  722. return styles;
  723. }
  724. /**
  725. * 根据Excel注解创建表格样式
  726. *
  727. * @param wb 工作薄对象
  728. * @return 自定义样式列表
  729. */
  730. private Map<String, CellStyle> annotationStyles(Workbook wb)
  731. {
  732. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  733. for (Object[] os : fields)
  734. {
  735. Excel excel = (Excel) os[1];
  736. String key = "data_" + excel.align() + "_" + excel.color();
  737. if (!styles.containsKey(key))
  738. {
  739. CellStyle style = wb.createCellStyle();
  740. style = wb.createCellStyle();
  741. style.setWrapText(true);
  742. style.setAlignment(excel.align());
  743. style.setVerticalAlignment(VerticalAlignment.CENTER);
  744. style.setBorderRight(BorderStyle.THIN);
  745. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  746. style.setBorderLeft(BorderStyle.THIN);
  747. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  748. style.setBorderTop(BorderStyle.THIN);
  749. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  750. style.setBorderBottom(BorderStyle.THIN);
  751. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  752. Font dataFont = wb.createFont();
  753. dataFont.setFontName("Arial");
  754. dataFont.setFontHeightInPoints((short) 11);
  755. dataFont.setColor(excel.color().index);
  756. style.setFont(dataFont);
  757. styles.put(key, style);
  758. }
  759. }
  760. return styles;
  761. }
  762. private Map<String, CellStyle> annotationStyles2(Workbook wb)
  763. {
  764. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  765. for (Object[] os : fields2)
  766. {
  767. Excelyw excel = (Excelyw) os[1];
  768. String key = "data_" + excel.align() + "_" + excel.color();
  769. if (!styles.containsKey(key))
  770. {
  771. CellStyle style = wb.createCellStyle();
  772. style = wb.createCellStyle();
  773. style.setWrapText(true);
  774. style.setAlignment(excel.align());
  775. style.setVerticalAlignment(VerticalAlignment.CENTER);
  776. style.setBorderRight(BorderStyle.THIN);
  777. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  778. style.setBorderLeft(BorderStyle.THIN);
  779. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  780. style.setBorderTop(BorderStyle.THIN);
  781. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  782. style.setBorderBottom(BorderStyle.THIN);
  783. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  784. Font dataFont = wb.createFont();
  785. dataFont.setFontName("Arial");
  786. dataFont.setFontHeightInPoints((short) 11);
  787. dataFont.setColor(excel.color().index);
  788. style.setFont(dataFont);
  789. styles.put(key, style);
  790. }
  791. }
  792. return styles;
  793. }
  794. /**
  795. * 创建单元格
  796. */
  797. public Cell createCell(Excel attr, Row row, int column)
  798. {
  799. String key = "data_" + attr.align() + "_" + attr.color();
  800. // 创建列
  801. Cell cell = row.createCell(column);
  802. row.setHeightInPoints(30);
  803. // 写入列信息
  804. cell.setCellValue(attr.name());
  805. setDataValidation(attr, row, column);
  806. cell.setCellStyle(styles.get("header"));
  807. return cell;
  808. }
  809. public Cell createCell2(Excelyw attr, Row row2, int column)
  810. {
  811. // 创建列
  812. Cell cell2 = row2.createCell(column);
  813. row2.setHeightInPoints(30);
  814. // 写入列信息
  815. cell2.setCellValue(attr.name());
  816. setDataValidation2(attr, row2, column);
  817. cell2.setCellStyle(styles2.get("header"));
  818. return cell2;
  819. }
  820. /**
  821. * 设置单元格信息
  822. *
  823. * @param value 单元格值
  824. * @param attr 注解相关
  825. * @param cell 单元格信息
  826. */
  827. public void setCellVo(Object value, Excel attr, Cell cell)
  828. {
  829. if (ColumnType.STRING == attr.cellType())
  830. {
  831. String cellValue = Convert.toStr(value);
  832. // 对于任何以表达式触发字符 =-+@开头的单元格,直接使用tab字符作为前缀,防止CSV注入。
  833. if (StringUtils.startsWithAny(cellValue, FORMULA_STR))
  834. {
  835. cellValue = RegExUtils.replaceFirst(cellValue, FORMULA_REGEX_STR, "\t$0");
  836. }
  837. cell.setCellValue(StringUtils.isNull(cellValue) ? attr.defaultValue() : cellValue + attr.suffix());
  838. }
  839. else if (ColumnType.NUMERIC == attr.cellType())
  840. {
  841. if (StringUtils.isNotNull(value))
  842. {
  843. cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
  844. }
  845. }
  846. else if (ColumnType.IMAGE == attr.cellType())
  847. {
  848. ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
  849. String imagePath = Convert.toStr(value);
  850. if (StringUtils.isNotEmpty(imagePath))
  851. {
  852. byte[] data = ImageUtils.getImage(imagePath);
  853. getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
  854. cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
  855. }
  856. }
  857. }
  858. public void setCellVo2(Object value, Excelyw attr, Cell cell)
  859. {
  860. if (Excelyw.ColumnType.STRING == attr.cellType())
  861. {
  862. String cellValue = Convert.toStr(value);
  863. // 对于任何以表达式触发字符 =-+@开头的单元格,直接使用tab字符作为前缀,防止CSV注入。
  864. if (StringUtils.startsWithAny(cellValue, FORMULA_STR))
  865. {
  866. cellValue = RegExUtils.replaceFirst(cellValue, FORMULA_REGEX_STR, "\t$0");
  867. }
  868. cell.setCellValue(StringUtils.isNull(cellValue) ? attr.defaultValue() : cellValue + attr.suffix());
  869. }
  870. else if (Excelyw.ColumnType.NUMERIC == attr.cellType())
  871. {
  872. if (StringUtils.isNotNull(value))
  873. {
  874. cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
  875. }
  876. }
  877. else if (Excelyw.ColumnType.IMAGE == attr.cellType())
  878. {
  879. ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
  880. String imagePath = Convert.toStr(value);
  881. if (StringUtils.isNotEmpty(imagePath))
  882. {
  883. byte[] data = ImageUtils.getImage(imagePath);
  884. getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
  885. cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
  886. }
  887. }
  888. }
  889. /**
  890. * 获取画布
  891. */
  892. public static Drawing<?> getDrawingPatriarch(Sheet sheet)
  893. {
  894. if (sheet.getDrawingPatriarch() == null)
  895. {
  896. sheet.createDrawingPatriarch();
  897. }
  898. return sheet.getDrawingPatriarch();
  899. }
  900. /**
  901. * 获取图片类型,设置图片插入类型
  902. */
  903. public int getImageType(byte[] value)
  904. {
  905. String type = FileTypeUtils.getFileExtendName(value);
  906. if ("JPG".equalsIgnoreCase(type))
  907. {
  908. return Workbook.PICTURE_TYPE_JPEG;
  909. }
  910. else if ("PNG".equalsIgnoreCase(type))
  911. {
  912. return Workbook.PICTURE_TYPE_PNG;
  913. }
  914. return Workbook.PICTURE_TYPE_JPEG;
  915. }
  916. /**
  917. * 创建表格样式
  918. */
  919. public void setDataValidation(Excel attr, Row row, int column)
  920. {
  921. if (attr.name().indexOf("注:") >= 0)
  922. {
  923. sheet.setColumnWidth(column, 6000);
  924. }
  925. else
  926. {
  927. // 设置列宽
  928. sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
  929. }
  930. if (StringUtils.isNotEmpty(attr.prompt()) || attr.combo().length > 0)
  931. {
  932. // 提示信息或只能选择不能输入的列内容.
  933. setPromptOrValidation(sheet, attr.combo(), attr.prompt(), 1, 100, column, column);
  934. }
  935. }
  936. public void setDataValidation2(Excelyw attr, Row row2, int column)
  937. {
  938. if (attr.name().indexOf("注:") >= 0)
  939. {
  940. sheet2.setColumnWidth(column, 6000);
  941. }
  942. else
  943. {
  944. // 设置列宽
  945. sheet2.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
  946. }
  947. if (StringUtils.isNotEmpty(attr.prompt()) || attr.combo().length > 0)
  948. {
  949. // 提示信息或只能选择不能输入的列内容.
  950. setPromptOrValidation(sheet2, attr.combo(), attr.prompt(), 1, 100, column, column);
  951. }
  952. }
  953. /**
  954. * 添加单元格
  955. */
  956. public Cell addCell(Excel attr, Row row, T vo, Field field, int column)
  957. {
  958. Cell cell = null;
  959. try
  960. {
  961. // 设置行高
  962. row.setHeight(maxHeight);
  963. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
  964. if (attr.isExport())
  965. {
  966. // 创建cell
  967. cell = row.createCell(column);
  968. cell.setCellStyle(styles.get("data_" + attr.align() + "_" + attr.color()));
  969. // CellRangeAddress region = new CellRangeAddress(2, 7, 0, 0);
  970. // sheet.addMergedRegion(region);
  971. // 用于读取对象中的属性
  972. Object value = getTargetValue(vo, field, attr);
  973. String dateFormat = attr.dateFormat();
  974. String readConverterExp = attr.readConverterExp();
  975. String separator = attr.separator();
  976. String dictType = attr.dictType();
  977. if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
  978. {
  979. cell.setCellValue(parseDateToStr(dateFormat, value));
  980. }
  981. else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
  982. {
  983. cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
  984. }
  985. else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
  986. {
  987. cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));
  988. }
  989. else if (value instanceof BigDecimal && -1 != attr.scale())
  990. {
  991. cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());
  992. }
  993. else if (!attr.handler().equals(ExcelHandlerAdapter.class))
  994. {
  995. cell.setCellValue(dataFormatHandlerAdapter(value, attr));
  996. }
  997. else
  998. {
  999. // 设置列类型
  1000. setCellVo(value, attr, cell);
  1001. }
  1002. addStatisticsData(column, Convert.toStr(value), attr);
  1003. }
  1004. }
  1005. catch (Exception e)
  1006. {
  1007. log.error("导出Excel失败{}", e);
  1008. }
  1009. return cell;
  1010. }
  1011. public Cell addCell2(Excelyw attr, Row row2, T vo, Field field, int column)
  1012. {
  1013. Cell cell = null;
  1014. try
  1015. {
  1016. // 设置行高
  1017. row2.setHeight(maxHeight2);
  1018. // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
  1019. if (attr.isExport())
  1020. {
  1021. // 创建cell
  1022. cell = row2.createCell(column);
  1023. cell.setCellStyle(styles2.get("data_" + attr.align() + "_" + attr.color()));
  1024. // 用于读取对象中的属性
  1025. Object value = getTargetValue2(vo, field, attr);
  1026. String dateFormat = attr.dateFormat();
  1027. String readConverterExp = attr.readConverterExp();
  1028. String separator = attr.separator();
  1029. String dictType = attr.dictType();
  1030. if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
  1031. {
  1032. cell.setCellValue(parseDateToStr(dateFormat, value));
  1033. }
  1034. else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
  1035. {
  1036. cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
  1037. }
  1038. else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
  1039. {
  1040. cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator));
  1041. }
  1042. else if (value instanceof BigDecimal && -1 != attr.scale())
  1043. {
  1044. cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString());
  1045. }
  1046. else if (!attr.handler().equals(ExcelHandlerAdapter.class))
  1047. {
  1048. cell.setCellValue(dataFormatHandlerAdapter2(value, attr));
  1049. }
  1050. else
  1051. {
  1052. // 设置列类型
  1053. setCellVo2(value, attr, cell);
  1054. }
  1055. if (heBing==true){
  1056. CellRangeAddress region = new CellRangeAddress(2, (short)listyw.size()+1, 0, (short)0);
  1057. sheet2.addMergedRegion(region);
  1058. this.heBing=false;
  1059. }
  1060. addStatisticsData2(column, Convert.toStr(value), attr);
  1061. }
  1062. }
  1063. catch (Exception e)
  1064. {
  1065. log.error("导出Excel失败{}", e);
  1066. }
  1067. return cell;
  1068. }
  1069. /**
  1070. * 设置 POI XSSFSheet 单元格提示或选择框
  1071. *
  1072. * @param sheet 表单
  1073. * @param textlist 下拉框显示的内容
  1074. * @param promptContent 提示内容
  1075. * @param firstRow 开始行
  1076. * @param endRow 结束行
  1077. * @param firstCol 开始列
  1078. * @param endCol 结束列
  1079. */
  1080. public void setPromptOrValidation(Sheet sheet, String[] textlist, String promptContent, int firstRow, int endRow,
  1081. int firstCol, int endCol)
  1082. {
  1083. DataValidationHelper helper = sheet.getDataValidationHelper();
  1084. DataValidationConstraint constraint = textlist.length > 0 ? helper.createExplicitListConstraint(textlist) : helper.createCustomConstraint("DD1");
  1085. CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
  1086. DataValidation dataValidation = helper.createValidation(constraint, regions);
  1087. if (StringUtils.isNotEmpty(promptContent))
  1088. {
  1089. // 如果设置了提示信息则鼠标放上去提示
  1090. dataValidation.createPromptBox("", promptContent);
  1091. dataValidation.setShowPromptBox(true);
  1092. }
  1093. // 处理Excel兼容性问题
  1094. if (dataValidation instanceof XSSFDataValidation)
  1095. {
  1096. dataValidation.setSuppressDropDownArrow(true);
  1097. dataValidation.setShowErrorBox(true);
  1098. }
  1099. else
  1100. {
  1101. dataValidation.setSuppressDropDownArrow(false);
  1102. }
  1103. sheet.addValidationData(dataValidation);
  1104. }
  1105. /**
  1106. * 解析导出值 0=男,1=女,2=未知
  1107. *
  1108. * @param propertyValue 参数值
  1109. * @param converterExp 翻译注解
  1110. * @param separator 分隔符
  1111. * @return 解析后值
  1112. */
  1113. public static String convertByExp(String propertyValue, String converterExp, String separator)
  1114. {
  1115. StringBuilder propertyString = new StringBuilder();
  1116. String[] convertSource = converterExp.split(",");
  1117. for (String item : convertSource)
  1118. {
  1119. String[] itemArray = item.split("=");
  1120. if (StringUtils.containsAny(separator, propertyValue))
  1121. {
  1122. for (String value : propertyValue.split(separator))
  1123. {
  1124. if (itemArray[0].equals(value))
  1125. {
  1126. propertyString.append(itemArray[1] + separator);
  1127. break;
  1128. }
  1129. }
  1130. }
  1131. else
  1132. {
  1133. if (itemArray[0].equals(propertyValue))
  1134. {
  1135. return itemArray[1];
  1136. }
  1137. }
  1138. }
  1139. return StringUtils.stripEnd(propertyString.toString(), separator);
  1140. }
  1141. /**
  1142. * 反向解析值 男=0,女=1,未知=2
  1143. *
  1144. * @param propertyValue 参数值
  1145. * @param converterExp 翻译注解
  1146. * @param separator 分隔符
  1147. * @return 解析后值
  1148. */
  1149. public static String reverseByExp(String propertyValue, String converterExp, String separator)
  1150. {
  1151. StringBuilder propertyString = new StringBuilder();
  1152. String[] convertSource = converterExp.split(",");
  1153. for (String item : convertSource)
  1154. {
  1155. String[] itemArray = item.split("=");
  1156. if (StringUtils.containsAny(separator, propertyValue))
  1157. {
  1158. for (String value : propertyValue.split(separator))
  1159. {
  1160. if (itemArray[1].equals(value))
  1161. {
  1162. propertyString.append(itemArray[0] + separator);
  1163. break;
  1164. }
  1165. }
  1166. }
  1167. else
  1168. {
  1169. if (itemArray[1].equals(propertyValue))
  1170. {
  1171. return itemArray[0];
  1172. }
  1173. }
  1174. }
  1175. return StringUtils.stripEnd(propertyString.toString(), separator);
  1176. }
  1177. /**
  1178. * 解析字典值
  1179. *
  1180. * @param dictValue 字典值
  1181. * @param dictType 字典类型
  1182. * @param separator 分隔符
  1183. * @return 字典标签
  1184. */
  1185. public static String convertDictByExp(String dictValue, String dictType, String separator)
  1186. {
  1187. return DictUtils.getDictLabel(dictType, dictValue, separator);
  1188. }
  1189. /**
  1190. * 反向解析值字典值
  1191. *
  1192. * @param dictLabel 字典标签
  1193. * @param dictType 字典类型
  1194. * @param separator 分隔符
  1195. * @return 字典值
  1196. */
  1197. public static String reverseDictByExp(String dictLabel, String dictType, String separator)
  1198. {
  1199. return DictUtils.getDictValue(dictType, dictLabel, separator);
  1200. }
  1201. /**
  1202. * 数据处理器
  1203. *
  1204. * @param value 数据值
  1205. * @param excel 数据注解
  1206. * @return
  1207. */
  1208. public String dataFormatHandlerAdapter(Object value, Excel excel)
  1209. {
  1210. try
  1211. {
  1212. Object instance = excel.handler().newInstance();
  1213. Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class });
  1214. value = formatMethod.invoke(instance, value, excel.args());
  1215. }
  1216. catch (Exception e)
  1217. {
  1218. log.error("不能格式化数据 " + excel.handler(), e.getMessage());
  1219. }
  1220. return Convert.toStr(value);
  1221. }
  1222. public String dataFormatHandlerAdapter2(Object value, Excelyw excel)
  1223. {
  1224. try
  1225. {
  1226. Object instance = excel.handler().newInstance();
  1227. Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class });
  1228. value = formatMethod.invoke(instance, value, excel.args());
  1229. }
  1230. catch (Exception e)
  1231. {
  1232. log.error("不能格式化数据 " + excel.handler(), e.getMessage());
  1233. }
  1234. return Convert.toStr(value);
  1235. }
  1236. /**
  1237. * 合计统计信息
  1238. */
  1239. private void addStatisticsData(Integer index, String text, Excel entity)
  1240. {
  1241. if (entity != null && entity.isStatistics())
  1242. {
  1243. Double temp = 0D;
  1244. if (!statistics.containsKey(index))
  1245. {
  1246. statistics.put(index, temp);
  1247. }
  1248. try
  1249. {
  1250. temp = Double.valueOf(text);
  1251. }
  1252. catch (NumberFormatException e)
  1253. {
  1254. }
  1255. statistics.put(index, statistics.get(index) + temp);
  1256. }
  1257. }
  1258. private void addStatisticsData2(Integer index, String text, Excelyw entity)
  1259. {
  1260. if (entity != null && entity.isStatistics())
  1261. {
  1262. Double temp = 0D;
  1263. if (!statistics2.containsKey(index))
  1264. {
  1265. statistics2.put(index, temp);
  1266. }
  1267. try
  1268. {
  1269. temp = Double.valueOf(text);
  1270. }
  1271. catch (NumberFormatException e)
  1272. {
  1273. }
  1274. statistics2.put(index, statistics2.get(index) + temp);
  1275. }
  1276. }
  1277. /**
  1278. * 创建统计行
  1279. */
  1280. public void addStatisticsRow()
  1281. {
  1282. if (statistics.size() > 0)
  1283. {
  1284. Row row = sheet.createRow(sheet.getLastRowNum() + 1);
  1285. Set<Integer> keys = statistics.keySet();
  1286. Cell cell = row.createCell(0);
  1287. cell.setCellStyle(styles.get("total"));
  1288. cell.setCellValue("合计");
  1289. for (Integer key : keys)
  1290. {
  1291. cell = row.createCell(key);
  1292. cell.setCellStyle(styles.get("total"));
  1293. cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
  1294. }
  1295. statistics.clear();
  1296. }
  1297. }
  1298. public void addStatisticsRow2()
  1299. {
  1300. if (statistics2.size() > 0)
  1301. {
  1302. Row row2 = sheet2.createRow(sheet2.getLastRowNum() + 1);
  1303. Set<Integer> keys = statistics.keySet();
  1304. Cell cell = row2.createCell(0);
  1305. cell.setCellStyle(styles2.get("total"));
  1306. cell.setCellValue("合计");
  1307. for (Integer key : keys)
  1308. {
  1309. cell = row2.createCell(key);
  1310. cell.setCellStyle(styles2.get("total"));
  1311. cell.setCellValue(DOUBLE_FORMAT.format(statistics2.get(key)));
  1312. }
  1313. statistics2.clear();
  1314. }
  1315. }
  1316. /**
  1317. * 编码文件名
  1318. */
  1319. public String encodingFilename(String filename)
  1320. {
  1321. filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
  1322. return filename;
  1323. }
  1324. /**
  1325. * 获取下载路径
  1326. *
  1327. * @param filename 文件名称
  1328. */
  1329. public String getAbsoluteFile(String filename)
  1330. {
  1331. String downloadPath = RuoYiConfig.getDownloadPath() + filename;
  1332. File desc = new File(downloadPath);
  1333. if (!desc.getParentFile().exists())
  1334. {
  1335. desc.getParentFile().mkdirs();
  1336. }
  1337. return downloadPath;
  1338. }
  1339. /**
  1340. * 获取bean中的属性值
  1341. *
  1342. * @param vo 实体对象
  1343. * @param field 字段
  1344. * @param excel 注解
  1345. * @return 最终的属性值
  1346. * @throws Exception
  1347. */
  1348. private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
  1349. {
  1350. Object o = field.get(vo);
  1351. if (StringUtils.isNotEmpty(excel.targetAttr()))
  1352. {
  1353. String target = excel.targetAttr();
  1354. if (target.contains("."))
  1355. {
  1356. String[] targets = target.split("[.]");
  1357. for (String name : targets)
  1358. {
  1359. o = getValue(o, name);
  1360. }
  1361. }
  1362. else
  1363. {
  1364. o = getValue(o, target);
  1365. }
  1366. }
  1367. return o;
  1368. }
  1369. private Object getTargetValue2(T vo, Field field, Excelyw excel) throws Exception
  1370. {
  1371. Object o = field.get(vo);
  1372. if (StringUtils.isNotEmpty(excel.targetAttr()))
  1373. {
  1374. String target = excel.targetAttr();
  1375. if (target.contains("."))
  1376. {
  1377. String[] targets = target.split("[.]");
  1378. for (String name : targets)
  1379. {
  1380. o = getValue(o, name);
  1381. }
  1382. }
  1383. else
  1384. {
  1385. o = getValue(o, target);
  1386. }
  1387. }
  1388. return o;
  1389. }
  1390. /**
  1391. * 以类的属性的get方法方法形式获取值
  1392. *
  1393. * @param o
  1394. * @param name
  1395. * @return value
  1396. * @throws Exception
  1397. */
  1398. private Object getValue(Object o, String name) throws Exception
  1399. {
  1400. if (StringUtils.isNotNull(o) && StringUtils.isNotEmpty(name))
  1401. {
  1402. Class<?> clazz = o.getClass();
  1403. Field field = clazz.getDeclaredField(name);
  1404. field.setAccessible(true);
  1405. o = field.get(o);
  1406. }
  1407. return o;
  1408. }
  1409. /**
  1410. * 得到所有定义字段
  1411. */
  1412. private void createExcelField()
  1413. {
  1414. this.fields = getFields();
  1415. this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
  1416. this.maxHeight = getRowHeight();
  1417. }
  1418. private void createExcelField2()
  1419. {
  1420. this.fields2 = getFields2();
  1421. this.fields2 = this.fields2.stream().sorted(Comparator.comparing(objects -> ((Excelyw) objects[1]).sort())).collect(Collectors.toList());
  1422. this.maxHeight2 = getRowHeight2();
  1423. }
  1424. /**
  1425. * 获取字段注解信息
  1426. */
  1427. public List<Object[]> getFields()
  1428. {
  1429. List<Object[]> fields = new ArrayList<Object[]>();
  1430. List<Field> tempFields = new ArrayList<>();
  1431. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
  1432. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
  1433. for (Field field : tempFields)
  1434. {
  1435. // 单注解
  1436. if (field.isAnnotationPresent(Excel.class))
  1437. {
  1438. Excel attr = field.getAnnotation(Excel.class);
  1439. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  1440. {
  1441. field.setAccessible(true);
  1442. fields.add(new Object[] { field, attr });
  1443. }
  1444. }
  1445. // 多注解
  1446. if (field.isAnnotationPresent(Excels.class))
  1447. {
  1448. Excels attrs = field.getAnnotation(Excels.class);
  1449. Excel[] excels = attrs.value();
  1450. for (Excel attr : excels)
  1451. {
  1452. if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
  1453. {
  1454. field.setAccessible(true);
  1455. fields.add(new Object[] { field, attr });
  1456. }
  1457. }
  1458. }
  1459. }
  1460. return fields;
  1461. }
  1462. public List<Object[]> getFields2()
  1463. {
  1464. List<Object[]> fields = new ArrayList<Object[]>();
  1465. List<Field> tempFields = new ArrayList<>();
  1466. tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
  1467. tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
  1468. for (Field field : tempFields)
  1469. {
  1470. // 单注解
  1471. if (field.isAnnotationPresent(Excelyw.class))
  1472. {
  1473. Excelyw attr = field.getAnnotation(Excelyw.class);
  1474. if (attr != null && (attr.type() == Excelyw.Type.ALL || attr.type() == type2))
  1475. {
  1476. field.setAccessible(true);
  1477. fields.add(new Object[] { field, attr });
  1478. }
  1479. }
  1480. // 多注解
  1481. if (field.isAnnotationPresent(Excelyws.class))
  1482. {
  1483. Excelyws attrs = field.getAnnotation(Excelyws.class);
  1484. Excelyw[] excels = attrs.value();
  1485. for (Excelyw attr : excels)
  1486. {
  1487. if (attr != null && (attr.type() == Excelyw.Type.ALL || attr.type() == type2))
  1488. {
  1489. field.setAccessible(true);
  1490. fields.add(new Object[] { field, attr });
  1491. }
  1492. }
  1493. }
  1494. }
  1495. return fields;
  1496. }
  1497. /**
  1498. * 根据注解获取最大行高
  1499. */
  1500. public short getRowHeight()
  1501. {
  1502. double maxHeight = 0;
  1503. for (Object[] os : this.fields)
  1504. {
  1505. Excel excel = (Excel) os[1];
  1506. maxHeight = Math.max(maxHeight, excel.height());
  1507. }
  1508. return (short) (maxHeight * 40);
  1509. }
  1510. public short getRowHeight2()
  1511. {
  1512. double maxHeight = 0;
  1513. for (Object[] os : this.fields2)
  1514. {
  1515. Excelyw excel = (Excelyw) os[1];
  1516. maxHeight = Math.max(maxHeight, excel.height());
  1517. }
  1518. return (short) (maxHeight * 100);
  1519. }
  1520. /**
  1521. * 创建一个工作簿
  1522. */
  1523. public void createWorkbook()
  1524. {
  1525. this.wb = new SXSSFWorkbook(500);
  1526. this.sheet = wb.createSheet();
  1527. this.sheet2 = wb.createSheet();
  1528. wb.setSheetName(0, sheetName);
  1529. wb.setSheetName(1, "业务类导出");
  1530. this.styles = createStyles(wb);
  1531. this.styles2 = createStyles2(wb);
  1532. }
  1533. /**
  1534. * 创建工作表
  1535. *
  1536. * @param sheetNo sheet数量
  1537. * @param index 序号
  1538. */
  1539. public void createSheet(int sheetNo, int index)
  1540. {
  1541. // 设置工作表的名称.
  1542. if (sheetNo > 1 && index > 0)
  1543. {
  1544. this.sheet = wb.createSheet();
  1545. this.createTitle();
  1546. wb.setSheetName(index, sheetName + index);
  1547. this.sheet2 = wb.createSheet();
  1548. this.createTitle2();
  1549. wb.setSheetName(1, sheetName + index);
  1550. }
  1551. }
  1552. /**
  1553. * 获取单元格值
  1554. *
  1555. * @param row 获取的行
  1556. * @param column 获取单元格列号
  1557. * @return 单元格值
  1558. */
  1559. public Object getCellValue(Row row, int column)
  1560. {
  1561. if (row == null)
  1562. {
  1563. return row;
  1564. }
  1565. Object val = "";
  1566. try
  1567. {
  1568. Cell cell = row.getCell(column);
  1569. if (StringUtils.isNotNull(cell))
  1570. {
  1571. if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
  1572. {
  1573. val = cell.getNumericCellValue();
  1574. if (DateUtil.isCellDateFormatted(cell))
  1575. {
  1576. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
  1577. }
  1578. else
  1579. {
  1580. if ((Double) val % 1 != 0)
  1581. {
  1582. val = new BigDecimal(val.toString());
  1583. }
  1584. else
  1585. {
  1586. val = new DecimalFormat("0").format(val);
  1587. }
  1588. }
  1589. }
  1590. else if (cell.getCellType() == CellType.STRING)
  1591. {
  1592. val = cell.getStringCellValue();
  1593. }
  1594. else if (cell.getCellType() == CellType.BOOLEAN)
  1595. {
  1596. val = cell.getBooleanCellValue();
  1597. }
  1598. else if (cell.getCellType() == CellType.ERROR)
  1599. {
  1600. val = cell.getErrorCellValue();
  1601. }
  1602. }
  1603. }
  1604. catch (Exception e)
  1605. {
  1606. return val;
  1607. }
  1608. return val;
  1609. }
  1610. /**
  1611. * 判断是否是空行
  1612. *
  1613. * @param row 判断的行
  1614. * @return
  1615. */
  1616. private boolean isRowEmpty(Row row)
  1617. {
  1618. if (row == null)
  1619. {
  1620. return true;
  1621. }
  1622. for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
  1623. {
  1624. Cell cell = row.getCell(i);
  1625. if (cell != null && cell.getCellType() != CellType.BLANK)
  1626. {
  1627. return false;
  1628. }
  1629. }
  1630. return true;
  1631. }
  1632. /**
  1633. * 获取Excel2003图片
  1634. *
  1635. * @param sheet 当前sheet对象
  1636. * @param workbook 工作簿对象
  1637. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1638. */
  1639. public static Map<String, PictureData> getSheetPictures03(HSSFSheet sheet, HSSFWorkbook workbook)
  1640. {
  1641. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1642. List<HSSFPictureData> pictures = workbook.getAllPictures();
  1643. if (!pictures.isEmpty())
  1644. {
  1645. for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren())
  1646. {
  1647. HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
  1648. if (shape instanceof HSSFPicture)
  1649. {
  1650. HSSFPicture pic = (HSSFPicture) shape;
  1651. int pictureIndex = pic.getPictureIndex() - 1;
  1652. HSSFPictureData picData = pictures.get(pictureIndex);
  1653. String picIndex = String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1());
  1654. sheetIndexPicMap.put(picIndex, picData);
  1655. }
  1656. }
  1657. return sheetIndexPicMap;
  1658. }
  1659. else
  1660. {
  1661. return sheetIndexPicMap;
  1662. }
  1663. }
  1664. /**
  1665. * 获取Excel2007图片
  1666. *
  1667. * @param sheet 当前sheet对象
  1668. * @param workbook 工作簿对象
  1669. * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
  1670. */
  1671. public static Map<String, PictureData> getSheetPictures07(XSSFSheet sheet, XSSFWorkbook workbook)
  1672. {
  1673. Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
  1674. for (POIXMLDocumentPart dr : sheet.getRelations())
  1675. {
  1676. if (dr instanceof XSSFDrawing)
  1677. {
  1678. XSSFDrawing drawing = (XSSFDrawing) dr;
  1679. List<XSSFShape> shapes = drawing.getShapes();
  1680. for (XSSFShape shape : shapes)
  1681. {
  1682. if (shape instanceof XSSFPicture)
  1683. {
  1684. XSSFPicture pic = (XSSFPicture) shape;
  1685. XSSFClientAnchor anchor = pic.getPreferredSize();
  1686. CTMarker ctMarker = anchor.getFrom();
  1687. String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol();
  1688. sheetIndexPicMap.put(picIndex, pic.getPictureData());
  1689. }
  1690. }
  1691. }
  1692. }
  1693. return sheetIndexPicMap;
  1694. }
  1695. /**
  1696. * 格式化不同类型的日期对象
  1697. *
  1698. * @param dateFormat 日期格式
  1699. * @param val 被格式化的日期对象
  1700. * @return 格式化后的日期字符
  1701. */
  1702. public String parseDateToStr(String dateFormat, Object val)
  1703. {
  1704. if (val == null)
  1705. {
  1706. return "";
  1707. }
  1708. String str;
  1709. if (val instanceof Date)
  1710. {
  1711. str = DateUtils.parseDateToStr(dateFormat, (Date) val);
  1712. }
  1713. else if (val instanceof LocalDateTime)
  1714. {
  1715. str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDateTime) val));
  1716. }
  1717. else if (val instanceof LocalDate)
  1718. {
  1719. str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDate) val));
  1720. }
  1721. else
  1722. {
  1723. str = val.toString();
  1724. }
  1725. return str;
  1726. }
  1727. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/595027
推荐阅读
相关标签
  

闽ICP备14008679号