Kaynağa Gözat

1.新增将excel转html文件工具类

GouGengquan 9 ay önce
ebeveyn
işleme
72393b9b3d

+ 12 - 118
biz-base/src/test/java/com/dayou/ExcelSimpleTests.java

@@ -2,24 +2,17 @@ package com.dayou;
 
 import com.alibaba.excel.EasyExcel;
 import com.alibaba.excel.ExcelReader;
-import com.alibaba.excel.ExcelWriter;
 import com.alibaba.excel.annotation.ExcelProperty;
 import com.alibaba.excel.read.listener.PageReadListener;
 import com.alibaba.excel.read.metadata.ReadSheet;
-import com.alibaba.excel.write.metadata.WriteSheet;
-import com.alibaba.fastjson2.JSON;
 import com.dayou.utils.EasyExcelUtil;
-import lombok.Builder;
+import com.dayou.utils.ExcelConvertToHtmlUtil;
 import lombok.Data;
 import lombok.NoArgsConstructor;
 import org.apache.poi.ss.usermodel.*;
-import org.apache.poi.ss.util.CellRangeAddressList;
-import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 import org.junit.jupiter.api.Test;
 
-import java.io.FileOutputStream;
 import java.io.IOException;
-import java.io.InputStream;
 import java.nio.file.Files;
 import java.nio.file.Paths;
 import java.util.HashMap;
@@ -45,20 +38,6 @@ public class ExcelSimpleTests {
         dataMap.put("b", 79.78);
 
         EasyExcelUtil.fillExcelDataByMap(templateFilePath, outputPath, dataMap, true);
-
-        /*// 使用EasyExcel填充数据
-        ExcelWriter excelWriter = EasyExcel.write(outputPath)
-                .withTemplate(templateFilePath)
-                .inMemory(true) // 启用内存模式
-                .build();
-        WriteSheet writeSheet = EasyExcel.writerSheet().build();
-        excelWriter.fill(dataMap, writeSheet); // 填充数据
-
-        // 由于填充后不会自动更新公式值,所以此处需要手动更新,大文件慎用(可能会导致内存溢出)
-        Workbook workbook = excelWriter.writeContext().writeWorkbookHolder().getWorkbook();
-        workbook.getCreationHelper().createFormulaEvaluator().evaluateAll(); // 强制计算公式
-
-        excelWriter.finish();*/
     }
 
     /**
@@ -74,102 +53,6 @@ public class ExcelSimpleTests {
 
          Workbook workbook = EasyExcelUtil.mergeExcel(sourceExcelPath, targetExcelPath, targetSheetIndex, targetRowNum, 0);
          workbook.write(Files.newOutputStream(Paths.get("E:\\test\\merge.xlsx")));
-
-        // 加载源Excel工作簿
-/*        try (InputStream inputStream = Files.newInputStream(Paths.get(sourceExcelPath))) {
-            Workbook sourceWorkbook = new XSSFWorkbook(inputStream);
-            Sheet sourceSheet = sourceWorkbook.getSheetAt(0); // 读取第一个sheet
-
-            // 打开已存在的Excel工作簿
-            Workbook targetWorkbook = WorkbookFactory.create(Files.newInputStream(Paths.get(targetExcelPath)));
-            Sheet targetSheet = targetWorkbook.getSheetAt(targetSheetIndex); // 获取目标sheet
-
-            // 复制样式映射
-            Map<Short, Short> styleMap = copyCellStyle(sourceWorkbook, targetWorkbook);
-
-            // 复制行和单元格
-            for (Row sourceRow : sourceSheet) {
-                Row targetRow = targetSheet.createRow(targetRowNum + sourceRow.getRowNum());
-                for (Cell sourceCell : sourceRow) {
-                    Cell targetCell = targetRow.createCell(sourceCell.getColumnIndex());
-                    copyCell(sourceCell, targetCell, targetWorkbook, styleMap);
-                }
-            }
-
-            // 复制数据验证
-            copyDataValidations(sourceSheet, targetSheet);
-
-            // 保存目标Excel工作簿
-            try (FileOutputStream outputStream = new FileOutputStream("E:\\test\\merge.xlsx")) {
-                targetWorkbook.write(outputStream);
-            }
-        } catch (Exception e) {
-            e.printStackTrace();
-        }*/
-    }
-
-    /**
-     * 复制单元格样式
-     * @param srcBook
-     * @param desBook
-     * @return
-     */
-    private static Map<Short, Short> copyCellStyle(Workbook srcBook, Workbook desBook) {
-        Map<Short, Short> styleMap = new HashMap<>();
-        for (short i = 0; i < srcBook.getNumCellStyles(); i++) {
-            CellStyle srcStyle = srcBook.getCellStyleAt(i);
-            CellStyle desStyle = desBook.createCellStyle();
-            desStyle.cloneStyleFrom(srcStyle);
-            styleMap.put(srcStyle.getIndex(), desStyle.getIndex());
-        }
-        return styleMap;
-    }
-
-    /**
-     * 复制单元格
-     * @param srcCell
-     * @param desCell
-     * @param targetWorkbook
-     * @param styleMap
-     */
-    private static void copyCell(Cell srcCell, Cell desCell, Workbook targetWorkbook, Map<Short, Short> styleMap) {
-        // 判断单元格值类型
-        if (srcCell.getCellType() == CellType.NUMERIC) {
-            desCell.setCellValue(srcCell.getNumericCellValue());
-        } else if (srcCell.getCellType() == CellType.STRING) {
-            desCell.setCellValue(srcCell.getStringCellValue());
-        } else if (srcCell.getCellType() == CellType.BOOLEAN) {
-            desCell.setCellValue(srcCell.getBooleanCellValue());
-        } else if (srcCell.getCellType() == CellType.BLANK) {
-            desCell.setBlank();
-        } else if (srcCell.getCellType() == CellType.FORMULA) {
-            desCell.setCellFormula(srcCell.getCellFormula());
-        }
-
-        // 复制样式
-        desCell.setCellStyle(targetWorkbook.getCellStyleAt(styleMap.get(srcCell.getCellStyle().getIndex())));
-    }
-
-    /**
-     * 复制数据验证(下拉框)
-     * @param sourceSheet
-     * @param targetSheet
-     */
-    private static void copyDataValidations(Sheet sourceSheet, Sheet targetSheet) {
-        for (DataValidation validation : sourceSheet.getDataValidations()) {
-            // 设置要设置数据验证的单元格坐标
-            CellRangeAddressList regions = new CellRangeAddressList(validation.getRegions().getCellRangeAddress(0).getFirstRow() + 4,
-                    validation.getRegions().getCellRangeAddress(0).getLastRow() + 4,
-                    validation.getRegions().getCellRangeAddress(0).getFirstColumn(),
-                    validation.getRegions().getCellRangeAddress(0).getLastColumn());
-            // 获取数据源的数据验证信息
-            DataValidationHelper validationHelper = targetSheet.getDataValidationHelper();
-            DataValidationConstraint constraint = validation.getValidationConstraint();
-            // 新建数据验证
-            DataValidation newValidation = validationHelper.createValidation(constraint, regions);
-            // 在目标excel中设置数据验证
-            targetSheet.addValidationData(newValidation);
-        }
     }
 
     @Data
@@ -232,4 +115,15 @@ public class ExcelSimpleTests {
         System.out.println(list.size());
     }
 
+    /**
+     * 测试将excel文件转换成html
+     * @throws Exception
+     */
+    @Test
+    void test() throws Exception {
+        String sourcePath = "E:\\test\\excel\\merge.xlsx";
+        String htmlLocation =  "E:\\test\\excel\\merge.html";
+        System.out.println(ExcelConvertToHtmlUtil.readExcelToHtml(sourcePath, htmlLocation, true, "xlsx", "测试", "Sheet1"));
+    }
+
 }

Dosya farkı çok büyük olduğundan ihmal edildi
+ 2 - 1
biz-base/src/test/java/com/dayou/FreeMarkTest.java


+ 21 - 56
biz-base/src/test/java/com/dayou/WordSimpleTests.java

@@ -154,19 +154,6 @@ public class WordSimpleTests {
         fos.close();
     }
 
-    @Test
-    public void getStudentCourseDataTable() throws Exception {
-        DataTable dataTable = new DataTable("StudentCourse");
-        dataTable.getColumns().add("CourseName");
-        dataTable.getColumns().add("CourseName02");
-        for (int i = 0; i < 3; i++) {
-            DataRow datarow = dataTable.newRow();
-            dataTable.getRows().add(datarow);
-            datarow.set(0, "Course " + i);
-            datarow.set(1, "Name " + i);
-        }
-    }
-
     /**
      * 测试向word指定位置插入另一个word
      * 实测该方法无法插入页眉页脚
@@ -228,6 +215,27 @@ public class WordSimpleTests {
     }
 
     /**
+     * 测试将html转成word的文件插入到word中
+     * 如果插入后发现table样式收到影响,请检查是否是插入位置设置了段落样式等影响到了table
+     * @throws Exception
+     */
+    @Test
+    void testInsertWordTable() throws Exception {
+        //设置书签,指定文档拼接的位置(书签需要在模板中提前设置好,相当于标识符)
+        String bookmark = "insertTable";
+
+        // 主word文件
+        Document mainDoc = new Document("E:\\test\\word\\6_success_output.doc");
+
+        // 需要插入的word文件
+        Document subDoc = new Document("E:\\test\\word\\1730343284041.docx");
+
+        mainDoc = AsposeWordUtil.insertDocumentAfterBookMark(mainDoc, subDoc, bookmark, false);
+        // 保存文件
+        mainDoc.save("E:\\test\\word\\createTable.docx");
+    }
+
+    /**
      * (该方法实测不是很好用,建议先在模板设置好页眉页脚页码等相关设置)
      * 设置Word页眉
      * 不能先设置页脚,需要先设置页码后才能设置页脚内容
@@ -279,30 +287,6 @@ public class WordSimpleTests {
         builder.writeln();
         builder.write("债权价值分析报告·正文");
 
-/*        // 移动光标到页脚
-        builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
-
-        builder.getPageSetup().setFooterDistance(28.3465);
-
-        // 添加页脚线
-        Border borderFooter = builder.getParagraphFormat().getBorders().getTop();
-        // 设置阴影
-        borderFooter.setShadow(true);
-        // 设置间距
-        borderFooter.setDistanceFromText(0);
-        // 设置页眉线风格(此处单线)
-        borderFooter.setLineStyle(LineStyle.SINGLE);
-
-        // 字体宋体
-        builder.getFont().setName("宋体");
-        // 是否加粗
-        builder.getFont().setBold(false);
-        // 字号(9是小五字号)
-        builder.getFont().setSize(9);
-
-        // 设置页脚内容
-        builder.write("四川大友房地产土地资产评估有限公司");*/
-
         mainDoc.save("E:\\test\\word\\output.docx");
     }
 
@@ -315,23 +299,6 @@ public class WordSimpleTests {
         Document doc = new Document("E:\\test\\word\\output.docx");
         DocumentBuilder builder = new DocumentBuilder(doc);
 
-        //创建页脚 页码
-/*        HeaderFooter footer = new HeaderFooter(doc, HeaderFooterType.FOOTER_PRIMARY);
-        doc.getFirstSection().getHeadersFooters().add(footer);*/
-
-//        builder.getPageSetup().setPageStartingNumber(10); 这玩意没用,看文档没看出来到底用在什么地方的
-
-        //页脚段落
-/*        Paragraph footerpara = new Paragraph(doc);
-        footerpara.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
-        Run footerparaRun = new Run(doc);
-        footerparaRun.getFont().setName("Arial Narrow");
-        footerparaRun.getFont().setSize(9.0);//小5号字体
-        footerpara.appendChild(footerparaRun);
-        footerpara.appendField(FieldType.FIELD_PAGE, true);//当前页码
-        footerpara.appendChild(footerparaRun);
-        footer.appendChild(footerpara);*/
-
         // 移动光标到页脚
         builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
 
@@ -362,8 +329,6 @@ public class WordSimpleTests {
         doc.getFirstSection().getPageSetup().setSectionStart(SectionStart.CONTINUOUS);
         doc.getFirstSection().getPageSetup().setPageStartingNumber(2);
 
-//        builder.insertField("PAGE");
-
         doc.save("E:\\test\\word\\output.docx");
     }
 

+ 530 - 0
common/src/main/java/com/dayou/utils/ExcelConvertToHtmlUtil.java

@@ -0,0 +1,530 @@
+package com.dayou.utils;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.poi.hssf.usermodel.*;
+import org.apache.poi.hssf.util.HSSFColor;
+import org.apache.poi.ss.formula.CollaboratingWorkbooksEnvironment;
+import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.ss.util.CellRangeAddress;
+import org.apache.poi.xssf.usermodel.XSSFCellStyle;
+import org.apache.poi.xssf.usermodel.XSSFColor;
+import org.apache.poi.xssf.usermodel.XSSFFont;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+
+import java.io.*;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.text.DecimalFormat;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+public class ExcelConvertToHtmlUtil {
+
+    /**
+     * @param filePath     excel源文件文件的路径
+     * @param htmlLocation 生成的html文件的路径
+     * @param isWithStyle  是否需要表格样式 包含 字体 颜色 边框 对齐方式
+     * @param sheetName    要读取的sheet名字
+     * @throws Exception
+     */
+    public static String readExcelToHtml(String filePath, String htmlLocation, boolean isWithStyle, String type, String attname, String sheetName) throws Exception {
+        InputStream is = null;
+        String htmlExcel = null;
+        Map<String, String> stylemap = new HashMap<String, String>();
+        try {
+            // 不同文件类型处理不一样
+            if ("csv".equalsIgnoreCase(type)) {
+                htmlExcel = getCSVInfo(filePath, htmlLocation);
+                writeCSVTypeFile(htmlExcel, htmlLocation, stylemap, attname);
+            } else {
+                File sourcefile = new File(filePath);
+                is = Files.newInputStream(sourcefile.toPath());
+                Workbook wb = WorkbookFactory.create(is);
+                if (wb instanceof XSSFWorkbook) { // 03版excel处理方法
+                    XSSFWorkbook xWb = (XSSFWorkbook) wb;
+                    htmlExcel = getExcelInfo(xWb, isWithStyle, stylemap, sheetName);
+                } else if (wb instanceof HSSFWorkbook) { // 07及10版以后的excel处理方法
+                    HSSFWorkbook hWb = (HSSFWorkbook) wb;
+                    htmlExcel = getExcelInfo(hWb, isWithStyle, stylemap, sheetName);
+                }
+                writeFile(htmlExcel, htmlLocation, stylemap, attname);
+            }
+        } catch (Exception e) {
+            throw new RuntimeException("excel引用了外部文件或其他表格,系统找不到该文件!");
+        } finally {
+            try {
+                if (is != null)
+                    is.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return htmlLocation;
+    }
+
+    private static void getcscvvalue(BufferedReader reader, List col, String oldvalue, List list) {
+        String line = null;
+        try {
+            while ((line = reader.readLine()) != null) {
+                String[] item = line.split(",", -1);
+                boolean isbreak = false;
+                for (String s : item) {
+                    String value = s;
+                    if (value.endsWith("\"")) {
+                        value = oldvalue + value;
+                        col.add(value);
+                    } else if (item.length == 1) {
+                        value = oldvalue + value;
+                        getcscvvalue(reader, col, value, list);
+                        isbreak = true;
+                    } else if (value.startsWith("\"")) {
+                        getcscvvalue(reader, col, value, list);
+                        isbreak = true;
+                    } else {
+                        col.add(value);
+                    }
+                }
+                if (!isbreak) {
+                    list.add(col);
+                    col = new ArrayList();
+                }
+            }
+        } catch (IOException e) {
+        }
+    }
+
+    private static String getCSVInfo(String filePath, String htmlLocation) {
+        StringBuilder sb = new StringBuilder();
+        DataInputStream in = null;
+        try {
+            in = new DataInputStream(Files.newInputStream(Paths.get(filePath)));
+            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+            String line = null;
+            List list = new ArrayList();
+            while ((line = reader.readLine()) != null) {
+                String[] item = line.split(",");
+                List col = new ArrayList();
+                for (String value : item) {
+                    if (value.startsWith("\"")) {
+                        getcscvvalue(reader, col, value, list);
+                    } else {
+                        col.add(value);
+                    }
+                }
+                list.add(col);
+            }
+            sb.append("<table>");
+            for (Object object : list) {
+                List col = (List) object;
+                if (col == null || col.isEmpty()) {
+                    sb.append("<tr><td ></td></tr>");
+                }
+                sb.append("<tr>");
+                for (Object o : col) {
+                    String value = (String) o;
+                    if (value == null || value.isEmpty()) {
+                        sb.append("<td> </td>");
+                        continue;
+                    } else {
+                        sb.append("<td>").append(value).append("</td>");
+                    }
+                }
+                sb.append("</tr>");
+            }
+            sb.append("</table>");
+        } catch (IOException e) {
+            // TODO Auto-generated catch block
+            e.printStackTrace();
+        } finally {
+            try {
+                in.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return sb.toString();
+    }
+
+    /**
+     * 读取excel文件,返回转换后的html字符串
+     *
+     * @param wb          工作簿
+     * @param isWithStyle 是否带上样式
+     * @param stylemap    样式
+     * @return String
+     */
+    private static String getExcelInfo(Workbook wb, boolean isWithStyle, Map<String, String> stylemap, String sheetName) {
+        StringBuffer sb = new StringBuffer();
+        Sheet sheet = wb.getSheet(sheetName);// 获取指定名称Sheet的内容
+        int lastRowNum = sheet.getLastRowNum();
+        Map<String, String>[] map = getRowSpanColSpanMap(sheet);
+        sb.append("<table id='table_").append(sheetName).append("' ");
+        sb.append("class='block'");
+        sb.append(">");
+        Row row = null; // 兼容
+        Cell cell = null; // 兼容
+
+        for (int rowNum = sheet.getFirstRowNum(); rowNum <= lastRowNum; rowNum++) {
+            row = sheet.getRow(rowNum);
+            if (row == null) {
+                sb.append("<tr><td ></td></tr>");
+                continue;
+            }
+            sb.append("<tr>");
+            int lastColNum = row.getLastCellNum();
+            for (int colNum = 0; colNum <= lastColNum; colNum++) {
+                cell = row.getCell(colNum);
+                if (cell == null) { // 特殊情况 空白的单元格会返回null
+                    sb.append("<td> </td>");
+                    continue;
+                }
+                String stringValue = getCellValue(cell);
+                if (map[0].containsKey(rowNum + "," + colNum)) {
+                    String pointString = map[0].get(rowNum + "," + colNum);
+                    map[0].remove(rowNum + "," + colNum);
+                    int bottomeRow = Integer.parseInt(pointString.split(",")[0]);
+                    int bottomeCol = Integer.parseInt(pointString.split(",")[1]);
+                    int rowSpan = bottomeRow - rowNum + 1;
+                    int colSpan = bottomeCol - colNum + 1;
+                    sb.append("<td rowspan= '").append(rowSpan).append("' colspan= '").append(colSpan).append("' ");
+                } else if (map[1].containsKey(rowNum + "," + colNum)) {
+                    map[1].remove(rowNum + "," + colNum);
+                    continue;
+                } else {
+                    sb.append("<td ");
+                }
+
+                // 判断是否需要样式
+                if (isWithStyle) {
+                    dealExcelStyle(wb, sheet, cell, sb, stylemap);// 处理单元格样式
+                }
+
+                sb.append("><nobr>");
+                //如果单元格为空要判断该单元格是不是通过其他单元格计算得到的
+                if (stringValue == null || stringValue.trim().isEmpty()) {
+                    FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
+                    if (evaluator.evaluate(cell) != null) {
+                        //如果单元格的值是通过其他单元格计算来的,则通过单元格计算获取
+                        String cellnumber = evaluator.evaluate(cell).getNumberValue() + "";
+                        //如果单元格的值是小数,保留两位
+                        if (cellnumber.contains(".")) {
+                            String[] decimal = cellnumber.split("\\.");
+                            if (decimal[1].length() > 2) {
+                                int num1 = decimal[1].charAt(0) - '0';
+                                int num2 = decimal[1].charAt(1) - '0';
+                                int num3 = decimal[1].charAt(2) - '0';
+                                if (num3 == 9) {
+                                    num2 = 0;
+                                } else if (num3 >= 5) {
+                                    num2 = num2 + 1;
+                                }
+                                cellnumber = decimal[0] + "." + num1 + num2;
+                            }
+                        }
+                        stringValue = cellnumber;
+                    }
+                    assert stringValue != null;
+                    sb.append(stringValue.replace(String.valueOf((char) 160), " "));
+                } else {
+                    // 将ascii码为160的空格转换为html下的空格( )
+                    sb.append(stringValue.replace(String.valueOf((char) 160), " "));
+                }
+                sb.append("</nobr></td>");
+            }
+            sb.append("</tr>");
+        }
+        sb.append("</table>");
+        return sb.toString();
+    }
+
+
+    private static Map<String, String>[] getRowSpanColSpanMap(Sheet sheet) {
+        Map<String, String> map0 = new HashMap<String, String>();
+        Map<String, String> map1 = new HashMap<String, String>();
+        int mergedNum = sheet.getNumMergedRegions();
+        CellRangeAddress range = null;
+        for (int i = 0; i < mergedNum; i++) {
+            range = sheet.getMergedRegion(i);
+            int topRow = range.getFirstRow();
+            int topCol = range.getFirstColumn();
+            int bottomRow = range.getLastRow();
+            int bottomCol = range.getLastColumn();
+            map0.put(topRow + "," + topCol, bottomRow + "," + bottomCol);
+            int tempRow = topRow;
+            while (tempRow <= bottomRow) {
+                int tempCol = topCol;
+                while (tempCol <= bottomCol) {
+                    map1.put(tempRow + "," + tempCol, "");
+                    tempCol++;
+                }
+                tempRow++;
+            }
+            map1.remove(topRow + "," + topCol);
+        }
+        return new Map[]{map0, map1};
+    }
+
+    /**
+     * 获取表格单元格Cell内容
+     *
+     * @param cell 单元格
+     * @return String
+     */
+    private static String getCellValue(Cell cell) {
+        String result;
+        switch (cell.getCellType()) {
+            case NUMERIC:// 数字类型
+                if (DateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
+                    SimpleDateFormat sdf = null;
+                    if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
+                        sdf = new SimpleDateFormat("HH:mm");
+                    } else {// 日期
+                        sdf = new SimpleDateFormat("yyyy-MM-dd");
+                    }
+                    Date date = cell.getDateCellValue();
+                    result = sdf.format(date);
+                } else if (cell.getCellStyle().getDataFormat() == 58) {
+                    // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
+                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+                    double value = cell.getNumericCellValue();
+                    Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
+                    result = sdf.format(date);
+                } else {
+                    double value = cell.getNumericCellValue();
+                    CellStyle style = cell.getCellStyle();
+                    DecimalFormat format = new DecimalFormat();
+                    String temp = style.getDataFormatString();
+                    // 单元格设置成常规
+                    if (temp.equals("General")) {
+                        format.applyPattern("#");
+                    }
+                    result = format.format(value);
+                }
+                break;
+            case STRING:// String类型
+                result = cell.getRichStringCellValue().toString();
+                result = result.replace("\n", "<br>");
+                break;
+            default:
+                result = "";
+                break;
+        }
+        return result;
+    }
+
+    /**
+     * 处理表格样式
+     *
+     * @param wb    表格
+     * @param sheet sheet
+     * @param sb    html
+     */
+    private static void dealExcelStyle(Workbook wb, Sheet sheet, Cell cell, StringBuffer sb, Map<String, String> stylemap) {
+        CellStyle cellStyle = cell.getCellStyle();
+        if (cellStyle != null) {
+            HorizontalAlignment alignment = cellStyle.getAlignment();
+            VerticalAlignment verticalAlignment = cellStyle.getVerticalAlignment();
+            String _style = "vertical-align:" + convertVerticalAlignToHtml(verticalAlignment) + ";";
+            if (wb instanceof XSSFWorkbook) {
+                XSSFFont xf = ((XSSFCellStyle) cellStyle).getFont();
+                if (xf.getBold()){
+                    _style += "font-weight:400";
+                }
+                String align = convertAlignToHtml(alignment);
+                int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
+                _style += ";font-size: " + xf.getFontHeight() / 2 + "%;width:" + columnWidth + "px;text-align:" + align + ";";
+
+                XSSFColor xc = xf.getXSSFColor();
+                if (xc != null) {
+                    _style += "color:#" + xc.getARGBHex().substring(2) + ";";
+                }
+
+                XSSFColor bgColor = (XSSFColor) cellStyle.getFillForegroundColorColor();
+                if (bgColor != null) {
+                    _style += "background-color:#" + bgColor.getARGBHex().substring(2) + ";"; // 背景颜色
+                }
+                _style += getBorderStyle(0, cellStyle.getBorderTop().getCode(), ((XSSFCellStyle) cellStyle).getTopBorderXSSFColor());
+                _style += getBorderStyle(1, cellStyle.getBorderRight().getCode(), ((XSSFCellStyle) cellStyle).getRightBorderXSSFColor());
+                _style += getBorderStyle(2, cellStyle.getBorderBottom().getCode(), ((XSSFCellStyle) cellStyle).getBottomBorderXSSFColor());
+                _style += getBorderStyle(3, cellStyle.getBorderLeft().getCode(), ((XSSFCellStyle) cellStyle).getLeftBorderXSSFColor());
+            } else if (wb instanceof HSSFWorkbook) {
+                HSSFFont hf = ((HSSFCellStyle) cellStyle).getFont(wb);
+                short boldWeight = hf.getFontHeight();
+                short fontColor = hf.getColor();
+                HSSFPalette palette = ((HSSFWorkbook) wb).getCustomPalette(); // 类HSSFPalette用于求的颜色的国际标准形式
+                HSSFColor hc = palette.getColor(fontColor);
+                String align = convertAlignToHtml(alignment);
+                int columnWidth = sheet.getColumnWidth(cell.getColumnIndex());
+                _style += "font-weight:" + boldWeight + ";font-size: " + hf.getFontHeight() / 2 + "%;text-align:" + align + ";width:" + columnWidth + "px;";
+                String fontColorStr = convertToStardColor(hc);
+                if (fontColorStr != null && !fontColorStr.trim().isEmpty()) {
+                    _style += "color:" + fontColorStr + ";"; // 字体颜色
+                }
+                short bgColor = cellStyle.getFillForegroundColor();
+                hc = palette.getColor(bgColor);
+                String bgColorStr = convertToStardColor(hc);
+                if (bgColorStr != null && !bgColorStr.trim().isEmpty()) {
+                    _style += "background-color:" + bgColorStr + ";"; // 背景颜色
+                }
+                _style += getBorderStyle(palette, 0, cellStyle.getBorderTop().getCode(), cellStyle.getTopBorderColor());
+                _style += getBorderStyle(palette, 1, cellStyle.getBorderRight().getCode(), cellStyle.getRightBorderColor());
+                _style += getBorderStyle(palette, 3, cellStyle.getBorderLeft().getCode(), cellStyle.getLeftBorderColor());
+                _style += getBorderStyle(palette, 2, cellStyle.getBorderBottom().getCode(), cellStyle.getBottomBorderColor());
+            }
+            String calssname = "";
+            if (!stylemap.containsKey(_style)) {
+                int count = stylemap.size();
+                calssname = "td" + count;
+                stylemap.put(_style, calssname);
+            } else {
+                calssname = stylemap.get(_style);
+            }
+            if (!"".equals(calssname)) {
+                sb.append("class='").append(calssname).append("'");
+            }
+        }
+    }
+
+    /**
+     * 单元格内容的水平对齐方式
+     *
+     * @param alignment 水平对其样式
+     * @return String
+     */
+    private static String convertAlignToHtml(HorizontalAlignment alignment) {
+        String align = "center";
+        switch (alignment) {
+            case LEFT:
+                align = "left";
+                break;
+            case CENTER:
+                align = "center";
+                break;
+            case RIGHT:
+                align = "right";
+                break;
+            default:
+                break;
+        }
+        return align;
+    }
+
+    /**
+     * 单元格中内容的垂直排列方式
+     *
+     * @param verticalAlignment 垂直位置样式
+     * @return String
+     */
+    private static String convertVerticalAlignToHtml(VerticalAlignment verticalAlignment) {
+
+        String valign = "middle";
+        switch (verticalAlignment) {
+            case BOTTOM:
+                valign = "bottom";
+                break;
+            case CENTER:
+                valign = "middle";
+                break;
+            case TOP:
+                valign = "top";
+                break;
+            default:
+                break;
+        }
+        return valign;
+    }
+
+    private static String convertToStardColor(HSSFColor hc) {
+        StringBuilder sb = new StringBuilder();
+        if (hc != null) {
+            if (HSSFColor.HSSFColorPredefined.AUTOMATIC.getIndex() == hc.getIndex()) {
+                return null;
+            }
+            sb.append("#");
+            for (int i = 0; i < hc.getTriplet().length; i++) {
+                sb.append(fillWithZero(Integer.toHexString(hc.getTriplet()[i])));
+            }
+        }
+        return sb.toString();
+    }
+
+    private static String fillWithZero(String str) {
+        if (str != null && str.length() < 2) {
+            return "0" + str;
+        }
+        return str;
+    }
+
+    static String[] bordesr = {"border-top:", "border-right:", "border-bottom:", "border-left:"};
+    static String[] borderStyles = {"solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ", "solid ",
+            "solid ", "solid", "solid", "solid", "solid", "solid"};
+
+    private static String getBorderStyle(HSSFPalette palette, int b, short s, short t) {
+        if (s == 0)
+            return bordesr[b] + borderStyles[s] + "#000000 1px;";
+        String borderColorStr = convertToStardColor(palette.getColor(t));
+        borderColorStr = borderColorStr == null || borderColorStr.isEmpty() ? "#000000" : borderColorStr;
+        return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
+    }
+
+    private static String getBorderStyle(int b, short s, XSSFColor xc) {
+        if (s == 0)
+            return bordesr[b] + borderStyles[s] + "#000000 1px;";
+        if (xc != null) {
+            String borderColorStr = xc.getARGBHex();// t.getARGBHex();
+            borderColorStr = borderColorStr == null || borderColorStr.isEmpty() ? "#000000"
+                    : borderColorStr.substring(2);
+            return bordesr[b] + borderStyles[s] + borderColorStr + " 1px;";
+        }
+        return "";
+    }
+
+    /*
+     * @param content 生成的excel表格标签
+     *
+     * @param htmlPath 生成的html文件地址
+     */
+    private static void writeFile(String content, String htmlPath, Map<String, String> stylemap, String name) {
+        File file2 = new File(htmlPath);
+        StringBuilder sb = new StringBuilder();
+        try {
+            file2.createNewFile();// 创建文件
+            sb.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>").append(name).append("</title><style type=\"text/css\">");
+            sb.append("ul{list-style: none;max-width: calc(100%);padding: 0px;margin: 0px;overflow-x: scroll;white-space: nowrap;} ul li{padding: 3px 5px;display: inline-block;border-right: 1px solid #768893;} ul li.cur{color: #F59C25;} table{border-collapse:collapse;display:none;width:100%;} table.block{display: block;}");
+            for (Map.Entry<String, String> entry : stylemap.entrySet()) {
+                String mapKey = entry.getKey();
+                String mapValue = entry.getValue();
+                sb.append(" .").append(mapValue).append("{").append(mapKey).append("}");
+            }
+            sb.append("</style><script>");
+            sb.append("function changetab(i){var block = document.getElementsByClassName(\"block\");block[0].className = block[0].className.replace(\"block\",\"\");var cur = document.getElementsByClassName(\"cur\");cur[0].className = cur[0].className.replace(\"cur\",\"\");var curli = document.getElementById(\"li_\"+i);curli.className += ' cur';var curtable = document.getElementById(\"table_\"+i);curtable.className=' block';}");
+            sb.append("</script></head><body>");
+            sb.append("<div>");
+            sb.append(content);
+            sb.append("</div>");
+            sb.append("</body></html>");
+            FileUtils.write(file2, sb.toString(), "UTF-8");
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+    private static void writeCSVTypeFile(String content, String htmlPath, Map<String, String> stylemap, String name) {
+        File file2 = new File(htmlPath);
+        StringBuilder sb = new StringBuilder();
+        try {
+            file2.createNewFile();// 创建文件
+            sb.append("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>").append(name).append("</title><style type=\"text/css\">");
+            sb.append("ul{list-style: none;max-width: calc(100%);padding: 0px;margin: 0px;overflow-x: scroll;white-space: nowrap;} ul li{padding: 3px 5px;display: inline-block;border-right: 1px solid #768893;} ul li.cur{color: #F59C25;} table{border-collapse:collapse;width:100%;} td{border: solid #000000 1px; min-width: 200px;}");
+            sb.append("</style></head><body>");
+            sb.append("<div>");
+            sb.append(content);
+            sb.append("</div>");
+            sb.append("</body></html>");
+            FileUtils.write(file2, sb.toString(), "UTF-8");
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+    }
+
+}

+ 1 - 0
pom.xml

@@ -35,6 +35,7 @@
         <easyexcel.vsersion>4.0.3</easyexcel.vsersion>
         <poi.vsersion>5.2.3</poi.vsersion>
         <poi-ooxml.version>5.2.3</poi-ooxml.version>
+        <poi-ooxml-schemas.version>4.1.2</poi-ooxml-schemas.version>
         <commons-io.version>2.15.0</commons-io.version>
         <aspose-words.version>20.12</aspose-words.version>
         <jsoup.version>1.11.3</jsoup.version>