• 文档在线预览word、pdf、excel文件转html以实现文档在线预览


    目录

    一、前言

    以下代码分别提供基于aspose、pdfbox、spire来实现来实现txt、word、pdf、ppt、word等文件转图片的需求。

    1、aspose

    Aspose 是一家致力于.Net ,Java,SharePoint,JasperReports和SSRS组件的提供商,数十个国家的数千机构都有用过aspose组件,创建、编辑、转换或渲染 Office、OpenOffice、PDF、图像、ZIP、CAD、XPS、EPS、PSD 和更多文件格式。注意aspose是商用组件,未经授权导出文件里面都是是水印(尊重版权,远离破解版)。

    需要在项目的pom文件里添加如下依赖

    1. <dependency>
    2. <groupId>com.aspose</groupId>
    3. <artifactId>aspose-words</artifactId>
    4. <version>23.1</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>com.aspose</groupId>
    8. <artifactId>aspose-pdf</artifactId>
    9. <version>23.1</version>
    10. </dependency>
    11. <dependency>
    12. <groupId>com.aspose</groupId>
    13. <artifactId>aspose-cells</artifactId>
    14. <version>23.1</version>
    15. </dependency>
    16. <dependency>
    17. <groupId>com.aspose</groupId>
    18. <artifactId>aspose-slides</artifactId>
    19. <version>23.1</version>
    20. </dependency>

    2 、poi + pdfbox

    因为aspose和spire虽然好用,但是都是是商用组件,所以这里也提供使用开源库操作的方式的方式。

    POI是Apache软件基金会用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

    Apache PDFBox是一个开源Java库,支持PDF文档的开发和转换。 使用此库,您可以开发用于创建,转换和操作PDF文档的Java程序。

    需要在项目的pom文件里添加如下依赖

    1. <dependency>
    2. <groupId>org.apache.pdfbox</groupId>
    3. <artifactId>pdfbox</artifactId>
    4. <version>2.0.4</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>org.apache.poi</groupId>
    8. <artifactId>poi</artifactId>
    9. <version>5.2.0</version>
    10. </dependency>
    11. <dependency>
    12. <groupId>org.apache.poi</groupId>
    13. <artifactId>poi-ooxml</artifactId>
    14. <version>5.2.0</version>
    15. </dependency>
    16. <dependency>
    17. <groupId>org.apache.poi</groupId>
    18. <artifactId>poi-scratchpad</artifactId>
    19. <version>5.2.0</version>
    20. </dependency>
    21. <dependency>
    22. <groupId>org.apache.poi</groupId>
    23. <artifactId>poi-excelant</artifactId>
    24. <version>5.2.0</version>
    25. </dependency>

    3 spire

    spire一款专业的Office编程组件,涵盖了对Word、Excel、PPT、PDF等文件的读写、编辑、查看功能。spire提供免费版本,但是存在只能导出前3页以及只能导出前500行的限制,只要达到其一就会触发限制。需要超出前3页以及只能导出前500行的限制的这需要购买付费版(尊重版权,远离破解版)。这里使用免费版进行演示。

    spire在添加pom之前还得先添加maven仓库来源

    1. <repository>
    2. <id>com.e-iceblue</id>
    3. <name>e-iceblue</name>
    4. <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
    5. </repository>

    接着在项目的pom文件里添加如下依赖

    免费版:

    1. <dependency>
    2. <groupId>e-iceblue</groupId>
    3. <artifactId>spire.office.free</artifactId>
    4. <version>5.3.1</version>
    5. </dependency>

    付费版版:

    1. <dependency>
    2. <groupId>e-iceblue</groupId>
    3. <artifactId>spire.office</artifactId>
    4. <version>5.3.1</version>
    5. </dependency>

    二、将文件转换成html字符串

    1、将word文件转成html字符串

    1.1 使用aspose

    1. public static String wordToHtmlStr(String wordPath) {
    2. try {
    3. Document doc = new Document(wordPath); // Address是将要被转化的word文档
    4. String htmlStr = doc.toString();
    5. return htmlStr;
    6. } catch (Exception e) {
    7. e.printStackTrace();
    8. }
    9. return null;
    10. }

    验证结果:

    请添加图片描述

    1.2 使用poi

    1. public String wordToHtmlStr(String wordPath) throws TransformerException, IOException, ParserConfigurationException {
    2. String htmlStr = null;
    3. String ext = wordPath.substring(wordPath.lastIndexOf("."));
    4. if (ext.equals(".docx")) {
    5. htmlStr = word2007ToHtmlStr(wordPath);
    6. } else if (ext.equals(".doc")){
    7. htmlStr = word2003ToHtmlStr(wordPath);
    8. } else {
    9. throw new RuntimeException("文件格式不正确");
    10. }
    11. return htmlStr;
    12. }
    13. public String word2007ToHtmlStr(String wordPath) throws IOException {
    14. // 使用内存输出流
    15. try(ByteArrayOutputStream out = new ByteArrayOutputStream()){
    16. word2007ToHtmlOutputStream(wordPath, out);
    17. return out.toString();
    18. }
    19. }
    20. private void word2007ToHtmlOutputStream(String wordPath,OutputStream out) throws IOException {
    21. ZipSecureFile.setMinInflateRatio(-1.0d);
    22. InputStream in = Files.newInputStream(Paths.get(wordPath));
    23. XWPFDocument document = new XWPFDocument(in);
    24. XHTMLOptions options = XHTMLOptions.create().setIgnoreStylesIfUnused(false).setImageManager(new Base64EmbedImgManager());
    25. // 使用内存输出流
    26. XHTMLConverter.getInstance().convert(document, out, options);
    27. }
    28. private String word2003ToHtmlStr(String wordPath) throws TransformerException, IOException, ParserConfigurationException {
    29. org.w3c.dom.Document htmlDocument = word2003ToHtmlDocument(wordPath);
    30. // Transform document to string
    31. StringWriter writer = new StringWriter();
    32. TransformerFactory tf = TransformerFactory.newInstance();
    33. Transformer transformer = tf.newTransformer();
    34. transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    35. transformer.setOutputProperty(OutputKeys.METHOD, "html");
    36. transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    37. transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    38. transformer.transform(new DOMSource(htmlDocument), new StreamResult(writer));
    39. return writer.toString();
    40. }
    41. private org.w3c.dom.Document word2003ToHtmlDocument(String wordPath) throws IOException, ParserConfigurationException {
    42. InputStream input = Files.newInputStream(Paths.get(wordPath));
    43. HWPFDocument wordDocument = new HWPFDocument(input);
    44. WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
    45. DocumentBuilderFactory.newInstance().newDocumentBuilder()
    46. .newDocument());
    47. wordToHtmlConverter.setPicturesManager((content, pictureType, suggestedName, widthInches, heightInches) -> {
    48. System.out.println(pictureType);
    49. if (PictureType.UNKNOWN.equals(pictureType)) {
    50. return null;
    51. }
    52. BufferedImage bufferedImage = ImgUtil.toImage(content);
    53. String base64Img = ImgUtil.toBase64(bufferedImage, pictureType.getExtension());
    54. // 带图片的word,则将图片转为base64编码,保存在一个页面中
    55. StringBuilder sb = (new StringBuilder(base64Img.length() + "data:;base64,".length()).append("data:;base64,").append(base64Img));
    56. return sb.toString();
    57. });
    58. // 解析word文档
    59. wordToHtmlConverter.processDocument(wordDocument);
    60. return wordToHtmlConverter.getDocument();
    61. }

    1.3 使用spire

    1. public String wordToHtmlStr(String wordPath) throws IOException {
    2. try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
    3. Document document = new Document();
    4. document.loadFromFile(wordPath);
    5. document.saveToFile(outputStream, FileFormat.Html);
    6. return outputStream.toString();
    7. }
    8. }

    2、将pdf文件转成html字符串

    2.1 使用aspose

    1. public static String pdfToHtmlStr(String pdfPath) throws IOException, ParserConfigurationException {
    2. PDDocument document = PDDocument.load(new File(pdfPath));
    3. Writer writer = new StringWriter();
    4. new PDFDomTree().writeText(document, writer);
    5. writer.close();
    6. document.close();
    7. return writer.toString();
    8. }

    验证结果:

    请添加图片描述

    2.2 使用 poi + pbfbox

    1. public String pdfToHtmlStr(String pdfPath) throws IOException, ParserConfigurationException {
    2. PDDocument document = PDDocument.load(new File(pdfPath));
    3. Writer writer = new StringWriter();
    4. new PDFDomTree().writeText(document, writer);
    5. writer.close();
    6. document.close();
    7. return writer.toString();
    8. }

    2.3 使用spire

    1. public String pdfToHtmlStr(String pdfPath) throws IOException, ParserConfigurationException {
    2. try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
    3. PdfDocument pdf = new PdfDocument();
    4. pdf.loadFromFile(pdfPath);
    5. return outputStream.toString();
    6. }
    7. }

    3、将excel文件转成html字符串

    3.1 使用aspose

    1. public static String excelToHtmlStr(String excelPath) throws Exception {
    2. FileInputStream fileInputStream = new FileInputStream(excelPath);
    3. Workbook workbook = new XSSFWorkbook(fileInputStream);
    4. DataFormatter dataFormatter = new DataFormatter();
    5. FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
    6. Sheet sheet = workbook.getSheetAt(0);
    7. StringBuilder htmlStringBuilder = new StringBuilder();
    8. htmlStringBuilder.append("Excel to HTML using Java and POI library");
    9. htmlStringBuilder.append("");
    10. htmlStringBuilder.append("");
    11. for (Row row : sheet) {
    12. htmlStringBuilder.append("
    13. ");
    14. for (Cell cell : row) {
    15. CellType cellType = cell.getCellType();
    16. if (cellType == CellType.FORMULA) {
    17. formulaEvaluator.evaluateFormulaCell(cell);
    18. cellType = cell.getCachedFormulaResultType();
    19. }
    20. String cellValue = dataFormatter.formatCellValue(cell, formulaEvaluator);
    21. htmlStringBuilder.append("
    22. ");
    23. }
    24. htmlStringBuilder.append("
    25. ");
    26. }
    27. htmlStringBuilder.append("
    28. ").append(cellValue).append("
      "
      );
    29. return htmlStringBuilder.toString();
    30. }

    返回的html字符串:

    <html><head><title>Excel to HTML using Java and POI library</title><style>table, th, td { border: 1px solid black; }</style></head><body><table><tr><td>序号</td><td>姓名</td><td>性别</td><td>联系方式</td><td>地址</td></tr><tr><td>1</td><td>张晓玲</td><td></td><td>11111111111</td><td>上海市浦东新区xx路xx弄xx号</td></tr><tr><td>2</td><td>王小二</td><td></td><td>1222222</td><td>上海市浦东新区xx路xx弄xx号</td></tr><tr><td>1</td><td>张晓玲</td><td></td><td>11111111111</td><td>上海市浦东新区xx路xx弄xx号</td></tr><tr><td>2</td><td>王小二</td><td></td><td>1222222</td><td>上海市浦东新区xx路xx弄xx号</td></tr><tr><td>1</td><td>张晓玲</td><td></td><td>11111111111</td><td>上海市浦东新区xx路xx弄xx号</td></tr><tr><td>2</td><td>王小二</td><td></td><td>1222222</td><td>上海市浦东新区xx路xx弄xx号</td></tr><tr><td>1</td><td>张晓玲</td><td></td><td>11111111111</td><td>上海市浦东新区xx路xx弄xx号</td></tr><tr><td>2</td><td>王小二</td><td></td><td>1222222</td><td>上海市浦东新区xx路xx弄xx号</td></tr><tr><td>1</td><td>张晓玲</td><td></td><td>11111111111</td><td>上海市浦东新区xx路xx弄xx号</td></tr><tr><td>2</td><td>王小二</td><td></td><td>1222222</td><td>上海市浦东新区xx路xx弄xx号</td></tr><tr><td>1</td><td>张晓玲</td><td></td><td>11111111111</td><td>上海市浦东新区xx路xx弄xx号</td></tr><tr><td>2</td><td>王小二</td><td></td><td>1222222</td><td>上海市浦东新区xx路xx弄xx号</td></tr><tr><td>1</td><td>张晓玲</td><td></td><td>11111111111</td><td>上海市浦东新区xx路xx弄xx号</td></tr><tr><td>2</td><td>王小二</td><td></td><td>1222222</td><td>上海市浦东新区xx路xx弄xx号</td></tr></table></body></html>
    

    3.2 使用poi + pdfbox

    1. public String excelToHtmlStr(String excelPath) throws Exception {
    2. FileInputStream fileInputStream = new FileInputStream(excelPath);
    3. try (Workbook workbook = WorkbookFactory.create(new File(excelPath))){
    4. DataFormatter dataFormatter = new DataFormatter();
    5. FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
    6. org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
    7. StringBuilder htmlStringBuilder = new StringBuilder();
    8. htmlStringBuilder.append("Excel to HTML using Java and POI library");
    9. htmlStringBuilder.append("");
    10. htmlStringBuilder.append("");
    11. for (Row row : sheet) {
    12. htmlStringBuilder.append("
    13. ");
    14. for (Cell cell : row) {
    15. CellType cellType = cell.getCellType();
    16. if (cellType == CellType.FORMULA) {
    17. formulaEvaluator.evaluateFormulaCell(cell);
    18. cellType = cell.getCachedFormulaResultType();
    19. }
    20. String cellValue = dataFormatter.formatCellValue(cell, formulaEvaluator);
    21. htmlStringBuilder.append("
    22. ");
    23. }
    24. htmlStringBuilder.append("
    25. ");
    26. }
    27. htmlStringBuilder.append("
    28. ").append(cellValue).append("
      "
      );
    29. return htmlStringBuilder.toString();
    30. }
    31. }

    3.3 使用spire

    1. public String excelToHtmlStr(String excelPath) throws Exception {
    2. try(ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
    3. Workbook workbook = new Workbook();
    4. workbook.loadFromFile(excelPath);
    5. workbook.saveToStream(outputStream, com.spire.xls.FileFormat.HTML);
    6. return outputStream.toString();
    7. }
    8. }

    三、将文件转换成html,并生成html文件

    有时我们是需要的不仅仅返回html字符串,而是需要生成一个html文件这时应该怎么做呢?一个改动量小的做法就是使用org.apache.commons.io包下的FileUtils工具类写入目标地址:

    FileUtils类将html字符串生成html文件示例:

    首先需要引入pom:

    1. <dependency>
    2. <groupId>commons-io</groupId>
    3. <artifactId>commons-io</artifactId>
    4. <version>2.8.0</version>
    5. </dependency>

    相关代码:

    1. String htmlStr = FileConvertUtil.pdfToHtmlStr("D:\\书籍\\电子书\\小说\\历史小说\\最后的可汗.doc");
    2. FileUtils.write(new File("D:\\test\\doc.html"), htmlStr, "utf-8");

    除此之外,还可以对上面的代码进行一些调整,已实现生成html文件,代码调整如下:

    1、将word文件转换成html文件

    word原文件效果:

    请添加图片描述

    1.1 使用aspose

    1. public static void wordToHtml(String wordPath, String htmlPath) {
    2. try {
    3. File sourceFile = new File(wordPath);
    4. String path = htmlPath + File.separator + sourceFile.getName().substring(0, sourceFile.getName().lastIndexOf(".")) + ".html";
    5. File file = new File(path); // 新建一个空白pdf文档
    6. FileOutputStream os = new FileOutputStream(file);
    7. Document doc = new Document(wordPath); // Address是将要被转化的word文档
    8. HtmlSaveOptions options = new HtmlSaveOptions();
    9. options.setExportImagesAsBase64(true);
    10. options.setExportRelativeFontSize(true);
    11. doc.save(os, options);
    12. } catch (Exception e) {
    13. e.printStackTrace();
    14. }
    15. }

    转换成html的效果:

    请添加图片描述

    1.2 使用poi + pdfbox

    1. public void wordToHtml(String wordPath, String htmlPath) throws TransformerException, IOException, ParserConfigurationException {
    2. htmlPath = FileUtil.getNewFileFullPath(wordPath, htmlPath, "html");
    3. String ext = wordPath.substring(wordPath.lastIndexOf("."));
    4. if (ext.equals(".docx")) {
    5. word2007ToHtml(wordPath, htmlPath);
    6. } else if (ext.equals(".doc")){
    7. word2003ToHtml(wordPath, htmlPath);
    8. } else {
    9. throw new RuntimeException("文件格式不正确");
    10. }
    11. }
    12. public void word2007ToHtml(String wordPath, String htmlPath) throws TransformerException, IOException, ParserConfigurationException {
    13. //try(OutputStream out = Files.newOutputStream(Paths.get(path))){
    14. try(FileOutputStream out = new FileOutputStream(htmlPath)){
    15. word2007ToHtmlOutputStream(wordPath, out);
    16. }
    17. }
    18. private void word2007ToHtmlOutputStream(String wordPath,OutputStream out) throws IOException {
    19. ZipSecureFile.setMinInflateRatio(-1.0d);
    20. InputStream in = Files.newInputStream(Paths.get(wordPath));
    21. XWPFDocument document = new XWPFDocument(in);
    22. XHTMLOptions options = XHTMLOptions.create().setIgnoreStylesIfUnused(false).setImageManager(new Base64EmbedImgManager());
    23. // 使用内存输出流
    24. XHTMLConverter.getInstance().convert(document, out, options);
    25. }
    26. public void word2003ToHtml(String wordPath, String htmlPath) throws TransformerException, IOException, ParserConfigurationException {
    27. org.w3c.dom.Document htmlDocument = word2003ToHtmlDocument(wordPath);
    28. // 生成html文件地址
    29. try(OutputStream outStream = Files.newOutputStream(Paths.get(htmlPath))){
    30. DOMSource domSource = new DOMSource(htmlDocument);
    31. StreamResult streamResult = new StreamResult(outStream);
    32. TransformerFactory factory = TransformerFactory.newInstance();
    33. Transformer serializer = factory.newTransformer();
    34. serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    35. serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    36. serializer.setOutputProperty(OutputKeys.METHOD, "html");
    37. serializer.transform(domSource, streamResult);
    38. }
    39. }
    40. private org.w3c.dom.Document word2003ToHtmlDocument(String wordPath) throws IOException, ParserConfigurationException {
    41. InputStream input = Files.newInputStream(Paths.get(wordPath));
    42. HWPFDocument wordDocument = new HWPFDocument(input);
    43. WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
    44. DocumentBuilderFactory.newInstance().newDocumentBuilder()
    45. .newDocument());
    46. wordToHtmlConverter.setPicturesManager((content, pictureType, suggestedName, widthInches, heightInches) -> {
    47. System.out.println(pictureType);
    48. if (PictureType.UNKNOWN.equals(pictureType)) {
    49. return null;
    50. }
    51. BufferedImage bufferedImage = ImgUtil.toImage(content);
    52. String base64Img = ImgUtil.toBase64(bufferedImage, pictureType.getExtension());
    53. // 带图片的word,则将图片转为base64编码,保存在一个页面中
    54. StringBuilder sb = (new StringBuilder(base64Img.length() + "data:;base64,".length()).append("data:;base64,").append(base64Img));
    55. return sb.toString();
    56. });
    57. // 解析word文档
    58. wordToHtmlConverter.processDocument(wordDocument);
    59. return wordToHtmlConverter.getDocument();
    60. }

    转换成html的效果:

    请添加图片描述

    1.3 使用spire

    1. public void wordToHtml(String wordPath, String htmlPath) {
    2. htmlPath = FileUtil.getNewFileFullPath(wordPath, htmlPath, "html");
    3. Document document = new Document();
    4. document.loadFromFile(wordPath);
    5. document.saveToFile(htmlPath, FileFormat.Html);
    6. }

    转换成html的效果:

    因为使用的是免费版,存在页数和字数限制,需要完整功能的的可以选择付费版本。PS:这回76页的文档居然转成功了前50页。

    请添加图片描述

    2、将pdf文件转换成html文件

    图片版pdf原文件效果:

    请添加图片描述

    文字版pdf原文件效果:

    请添加图片描述

    2.1 使用aspose

    1. public static void pdfToHtml(String pdfPath, String htmlPath) throws IOException, ParserConfigurationException {
    2. File file = new File(pdfPath);
    3. String path = htmlPath + File.separator + file.getName().substring(0, file.getName().lastIndexOf(".")) + ".html";
    4. PDDocument document = PDDocument.load(new File(pdfPath));
    5. Writer writer = new PrintWriter(path, "UTF-8");
    6. new PDFDomTree().writeText(document, writer);
    7. writer.close();
    8. document.close();
    9. }

    图片版PDF文件验证结果:

    请添加图片描述

    文字版PDF文件验证结果:

    请添加图片描述

    2.2 使用poi + pdfbox

    1. public void pdfToHtml(String pdfPath, String htmlPath) throws IOException, ParserConfigurationException {
    2. String path = FileUtil.getNewFileFullPath(pdfPath, htmlPath, "html");
    3. PDDocument document = PDDocument.load(new File(pdfPath));
    4. Writer writer = new PrintWriter(path, "UTF-8");
    5. new PDFDomTree().writeText(document, writer);
    6. writer.close();
    7. document.close();
    8. }

    图片版PDF文件验证结果:

    请添加图片描述

    文字版PDF原文件效果:

    请添加图片描述

    2.3 使用spire

    1. public void pdfToHtml(String pdfPath, String htmlPath) throws IOException, ParserConfigurationException {
    2. htmlPath = FileUtil.getNewFileFullPath(pdfPath, htmlPath, "html");
    3. PdfDocument pdf = new PdfDocument();
    4. pdf.loadFromFile(pdfPath);
    5. pdf.saveToFile(htmlPath, com.spire.pdf.FileFormat.HTML);
    6. }

    图片版PDF文件验证结果:
    因为使用的是免费版,所以只有前三页是正常的。。。有超过三页需求的可以选择付费版本。

    请添加图片描述

    文字版PDF原文件效果:

    报错了无法转换。。。

    1. java.lang.NullPointerException
    2. at com.spire.pdf.PdfPageWidget.spr┢⅛(Unknown Source)
    3. at com.spire.pdf.PdfPageWidget.getSize(Unknown Source)
    4. at com.spire.pdf.PdfPageBase.spr†™—(Unknown Source)
    5. at com.spire.pdf.PdfPageBase.getActualSize(Unknown Source)
    6. at com.spire.pdf.PdfPageBase.getSection(Unknown Source)
    7. at com.spire.pdf.general.PdfDestination.spr︻┎—(Unknown Source)
    8. at com.spire.pdf.general.PdfDestination.spr┻┑—(Unknown Source)
    9. at com.spire.pdf.general.PdfDestination.getElement(Unknown Source)
    10. at com.spire.pdf.primitives.PdfDictionary.setProperty(Unknown Source)
    11. at com.spire.pdf.bookmarks.PdfBookmark.setDestination(Unknown Source)
    12. at com.spire.pdf.bookmarks.PdfBookmarkWidget.spr┭┘—(Unknown Source)
    13. at com.spire.pdf.bookmarks.PdfBookmarkWidget.getDestination(Unknown Source)
    14. at com.spire.pdf.PdfDocumentBase.spr╻⅝(Unknown Source)
    15. at com.spire.pdf.widget.PdfPageCollection.spr┦⅝(Unknown Source)
    16. at com.spire.pdf.widget.PdfPageCollection.removeAt(Unknown Source)
    17. at com.spire.pdf.PdfDocumentBase.spr┞⅝(Unknown Source)
    18. at com.spire.pdf.PdfDocument.loadFromFile(Unknown Source)

    3、将excel文件转换成html文件

    excel原文件效果:

    请添加图片描述

    3.1 使用aspose

    1. public void excelToHtml(String excelPath, String htmlPath) throws Exception {
    2. htmlPath = FileUtil.getNewFileFullPath(excelPath, htmlPath, "html");
    3. Workbook workbook = new Workbook(excelPath);
    4. com.aspose.cells.HtmlSaveOptions options = new com.aspose.cells.HtmlSaveOptions();
    5. workbook.save(htmlPath, options);
    6. }

    转换成html的效果:

    请添加图片描述

    3.2 使用poi

    1. public void excelToHtml(String excelPath, String htmlPath) throws Exception {
    2. String path = FileUtil.getNewFileFullPath(excelPath, htmlPath, "html");
    3. try(FileOutputStream fileOutputStream = new FileOutputStream(path)){
    4. String htmlStr = excelToHtmlStr(excelPath);
    5. byte[] bytes = htmlStr.getBytes();
    6. fileOutputStream.write(bytes);
    7. }
    8. }
    9. public String excelToHtmlStr(String excelPath) throws Exception {
    10. FileInputStream fileInputStream = new FileInputStream(excelPath);
    11. try (Workbook workbook = WorkbookFactory.create(new File(excelPath))){
    12. DataFormatter dataFormatter = new DataFormatter();
    13. FormulaEvaluator formulaEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
    14. org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
    15. StringBuilder htmlStringBuilder = new StringBuilder();
    16. htmlStringBuilder.append("Excel to HTML using Java and POI library");
    17. htmlStringBuilder.append("");
    18. htmlStringBuilder.append("");
    19. for (Row row : sheet) {
    20. htmlStringBuilder.append("
    21. ");
    22. for (Cell cell : row) {
    23. CellType cellType = cell.getCellType();
    24. if (cellType == CellType.FORMULA) {
    25. formulaEvaluator.evaluateFormulaCell(cell);
    26. cellType = cell.getCachedFormulaResultType();
    27. }
    28. String cellValue = dataFormatter.formatCellValue(cell, formulaEvaluator);
    29. htmlStringBuilder.append("
    30. ");
    31. }
    32. htmlStringBuilder.append("
    33. ");
    34. }
    35. htmlStringBuilder.append("
    36. ").append(cellValue).append("
      "
      );
    37. return htmlStringBuilder.toString();
    38. }
    39. }

    转换成html的效果:

    请添加图片描述

    3.3 使用spire

    1. public void excelToHtml(String excelPath, String htmlPath) throws Exception {
    2. htmlPath = FileUtil.getNewFileFullPath(excelPath, htmlPath, "html");
    3. Workbook workbook = new Workbook();
    4. workbook.loadFromFile(excelPath);
    5. workbook.saveToFile(htmlPath, com.spire.xls.FileFormat.HTML);
    6. }

    转换成html的效果:

    请添加图片描述

    四、总结

    从上述的效果展示我们可以发现其实转成html效果不是太理想,很多细节样式没有还原,这其实是因为这类转换往往都是追求目标是通过使用文档中的语义信息并忽略其他细节来生成简单干净的 HTML,所以在转换过程中复杂样式被忽略,比如居中、首行缩进、字体,文本大小,颜色。举个例子在转换是 会将应用标题 1 样式的任何段落转换为 h1 元素,而不是尝试完全复制标题的样式。所以转成html的显示效果往往和原文档不太一样。这意味着对于较复杂的文档而言,这种转换不太可能是完美的。但如果都是只使用简单样式文档或者对文档样式不太关心的这种方式也不妨一试。

    PS:如果想要展示效果好的话,其实可以将上篇文章《文档在线预览(一)通过将txt、word、pdf转成图片实现在线预览功能》说的内容和本文结合起来使用,即将文档里的内容都生成成图片(很可能是多张图片),然后将生成的图片全都放到一个html页面里 ,用html+css来保持样式并实现多张图片展示,再将html返回。开源组件kkfilevie就是用的就是这种做法。

    kkfileview展示效果如下:

    请添加图片描述

    下图是kkfileview返回的html代码,从html代码我们可以看到kkfileview其实是将文件(txt文件除外)每页的内容都转成了图片,然后将这些图片都嵌入到一个html里,再返回给用户一个html页面。 

    请添加图片描述

  • 相关阅读:
    【C语言程序设计】实验 5
    Mysql提取表字段中的字符串
    二叉搜索树解决硬木问题
    day06_循环
    torch实现Gated PixelCNN
    面试题-React(十二):React中不可变数据的力量
    CISP-PTE真题演示
    如何调整yolo混淆矩阵的大小,使其更加美观
    听觉刺激期间的神经血管耦合:ERPs和fNIRS血流动力学
    利用可视化结果,点击出现对应的句子
  • 原文地址:https://blog.csdn.net/2201_75761617/article/details/133236297