Sfoglia il codice sorgente

1.完善excel转html标记语言工具类

GouGengquan 9 mesi fa
parent
commit
350678e96d

+ 4 - 1
biz-base/src/test/java/com/dayou/ExcelSimpleTests.java

@@ -123,7 +123,10 @@ public class ExcelSimpleTests {
     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"));
+        // 将excel转为html并保存为html文件
+        System.out.println(ExcelConvertToHtmlUtil.readExcelToHtmlFile(sourcePath, htmlLocation, true, "xlsx", "Sheet1"));
+        // 将excel转为html并返回字符串
+        System.out.println(ExcelConvertToHtmlUtil.readExcelToHtmlCode(sourcePath, true, "xlsx","Sheet1"));
     }
 
 }

+ 97 - 33
common/src/main/java/com/dayou/utils/ExcelConvertToHtmlUtil.java

@@ -3,7 +3,6 @@ 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;
@@ -21,21 +20,65 @@ import java.util.*;
 public class ExcelConvertToHtmlUtil {
 
     /**
+     * 将excel指定名字的sheet转换为html标记语言并返回为字符串
+     * @param filePath     excel源文件文件的路径
+     * @param isWithStyle  是否需要表格样式 包含 字体 颜色 边框 对齐方式
+     * @param sheetName    要读取的sheet名字
+     * @param type excel文件类型
+     * @return String
+     */
+    public static String readExcelToHtmlCode(String filePath, boolean isWithStyle, String type, String sheetName){
+        InputStream is = null;
+        String htmlExcel = null;
+        Map<String, String> stylemap = new HashMap<String, String>();
+        try {
+            // 不同文件类型处理不一样
+            if ("csv".equalsIgnoreCase(type)) {
+                htmlExcel = getCSVInfo(filePath);
+            } 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);
+                }
+            }
+            htmlExcel = genHtmlCode(htmlExcel, stylemap, sheetName);
+        } catch (Exception e) {
+            throw new RuntimeException(e.getMessage());
+        } finally {
+            try {
+                if (is != null)
+                    is.close();
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+        return htmlExcel;
+    }
+
+    /**
+     * 将excel指定名字的sheet转换为html标记语言并保存为html文件
      * @param filePath     excel源文件文件的路径
      * @param htmlLocation 生成的html文件的路径
      * @param isWithStyle  是否需要表格样式 包含 字体 颜色 边框 对齐方式
      * @param sheetName    要读取的sheet名字
-     * @throws Exception
+     * @param type excel文件类型
+     * @return void
      */
-    public static String readExcelToHtml(String filePath, String htmlLocation, boolean isWithStyle, String type, String attname, String sheetName) throws Exception {
+    public static String readExcelToHtmlFile(String filePath, String htmlLocation, boolean isWithStyle, String type, 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);
+                htmlExcel = getCSVInfo(filePath);
+                writeCSVTypeFile(htmlExcel, htmlLocation, stylemap, sheetName);
             } else {
                 File sourcefile = new File(filePath);
                 is = Files.newInputStream(sourcefile.toPath());
@@ -47,10 +90,10 @@ public class ExcelConvertToHtmlUtil {
                     HSSFWorkbook hWb = (HSSFWorkbook) wb;
                     htmlExcel = getExcelInfo(hWb, isWithStyle, stylemap, sheetName);
                 }
-                writeFile(htmlExcel, htmlLocation, stylemap, attname);
+                writeFile(htmlExcel, htmlLocation, stylemap, sheetName);
             }
         } catch (Exception e) {
-            throw new RuntimeException("excel引用了外部文件或其他表格,系统找不到该文件!");
+            throw new RuntimeException(e.getMessage());
         } finally {
             try {
                 if (is != null)
@@ -93,7 +136,7 @@ public class ExcelConvertToHtmlUtil {
         }
     }
 
-    private static String getCSVInfo(String filePath, String htmlLocation) {
+    private static String getCSVInfo(String filePath) {
         StringBuilder sb = new StringBuilder();
         DataInputStream in = null;
         try {
@@ -486,45 +529,66 @@ public class ExcelConvertToHtmlUtil {
      */
     private static void writeFile(String content, String htmlPath, Map<String, String> stylemap, String name) {
         File file2 = new File(htmlPath);
-        StringBuilder sb = new StringBuilder();
+//        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");
+            FileUtils.write(file2, genHtmlCode(content, stylemap, name), "UTF-8");
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
 
+    /**
+     * 将html字符串拼接并返回
+     * @param content table内容
+     * @param stylemap 样式
+     * @param name 表格名
+     * @return String
+     */
+    private static String genHtmlCode(String content, Map<String, String> stylemap, String name){
+        StringBuilder sb = new StringBuilder();
+        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>");
+        return sb.toString();
+    }
+
     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");
+            FileUtils.write(file2, genCSVTypeHtmlCode(content, stylemap, name), "UTF-8");
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
 
+    /**
+     * 将CSV类型Excel的html字符串拼接并返回
+     * @param content table内容
+     * @param stylemap 样式
+     * @param name 表格名
+     * @return String
+     */
+    private static String genCSVTypeHtmlCode(String content, Map<String, String> stylemap, String name){
+        return "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><title>" + name + "</title><style type=\"text/css\">" +
+                "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;}" +
+                "</style></head><body>" +
+                "<div>" +
+                content +
+                "</div>" +
+                "</body></html>";
+    }
+
 }

+ 0 - 1
pom.xml

@@ -35,7 +35,6 @@
         <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>