You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
3.4 KiB

  1. package cn.afterturn.easypoi.util;
  2. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  3. import org.apache.poi.ss.usermodel.*;
  4. import java.util.Date;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. /**
  8. * poi 4.0 07版本在 shift操作下有bug,不移动了单元格以及单元格样式,没有移动cell
  9. * cell还是复用的原理的cell,导致wb输出的时候没有输出值
  10. * 等待修复的时候删除这个问题
  11. *
  12. * @author by jueyue on 19-6-17.
  13. */
  14. public class PoiExcelTempUtil {
  15. /**
  16. * 把这N行的数据,cell重新设置下,修复因为shift的浅复制问题,导致文本不显示的错误
  17. *
  18. * @param sheet
  19. * @param startRow
  20. * @param endRow
  21. */
  22. public static void reset(Sheet sheet, int startRow, int endRow) {
  23. if (sheet.getWorkbook() instanceof HSSFWorkbook) {
  24. return;
  25. }
  26. for (int i = startRow; i <= endRow; i++) {
  27. Row row = sheet.getRow(i);
  28. if (row == null) {
  29. continue;
  30. }
  31. int cellNum = row.getLastCellNum();
  32. for (int j = 0; j < cellNum; j++) {
  33. if (row.getCell(j) == null) {
  34. continue;
  35. }
  36. Map<String, Object> map = copyCell(row.getCell(j));
  37. row.removeCell(row.getCell(j));
  38. Cell cell = row.createCell(j);
  39. cell.setCellStyle((CellStyle) map.get("cellStyle"));
  40. if ((boolean) map.get("isDate")) {
  41. cell.setCellValue((Date) map.get("value"));
  42. } else {
  43. CellType cellType = (CellType) map.get("cellType");
  44. switch (cellType) {
  45. case NUMERIC:
  46. cell.setCellValue((double) map.get("value"));
  47. break;
  48. case STRING:
  49. cell.setCellValue((String) map.get("value"));
  50. case FORMULA:
  51. break;
  52. case BLANK:
  53. break;
  54. case BOOLEAN:
  55. cell.setCellValue((boolean) map.get("value"));
  56. case ERROR:
  57. break;
  58. }
  59. }
  60. }
  61. }
  62. }
  63. private static Map copyCell(Cell cell) {
  64. Map<String, Object> map = new HashMap<>();
  65. map.put("cellType", cell.getCellType());
  66. map.put("isDate", CellType.NUMERIC == cell.getCellType() && DateUtil.isCellDateFormatted(cell));
  67. map.put("value", getValue(cell));
  68. map.put("cellStyle", cell.getCellStyle());
  69. return map;
  70. }
  71. private static Object getValue(Cell cell) {
  72. if (CellType.NUMERIC == cell.getCellType() && DateUtil.isCellDateFormatted(cell)) {
  73. return cell.getDateCellValue();
  74. }
  75. switch (cell.getCellType()) {
  76. case _NONE:
  77. return null;
  78. case NUMERIC:
  79. return cell.getNumericCellValue();
  80. case STRING:
  81. return cell.getStringCellValue();
  82. case FORMULA:
  83. return cell.getCellFormula();
  84. case BLANK:
  85. break;
  86. case BOOLEAN:
  87. return cell.getBooleanCellValue();
  88. case ERROR:
  89. break;
  90. }
  91. return null;
  92. }
  93. }