N个功能片段之文件预览

java

1,maven依赖

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans</artifactId>
            <version>5.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.4</version>
        </dependency>

2,逻辑提取FileToHtmlUtils 


import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * 文件上传工具类
 *
 * @author ruoyi
 */
public class FileToHtmlUtils {

    public static String convertExcelToHtml(String filePath) throws IOException {
        FileInputStream fis = new FileInputStream(new File(filePath));
        Workbook workbook = new XSSFWorkbook(fis);
        Sheet sheet = workbook.getSheetAt(0);

        StringBuilder htmlContent = new StringBuilder();

        // 添加HTML和CSS样式(表格加边框)
        htmlContent.append("<html><body>")
                .append("<table style=\"width:100%; table-layout: fixed; border-collapse: collapse; border: 2px solid #333;\">");

        // 获取列数并添加 colgroup 设置每列宽度
        Row firstRow = sheet.getRow(0);
        int columnCount = firstRow != null ? firstRow.getLastCellNum() : 0;

        // 插入 <colgroup> 设置列宽
        htmlContent.append("<colgroup>");
        for (int i = 0; i < columnCount; i++) {
            switch (i) {
                case 0:
                    htmlContent.append("<col style=\"width:100px\">");
                    break;
                case 1:
                case 2:
                case 3:
                    htmlContent.append("<col style=\"width:100px\">");
                    break;
                default:
                    htmlContent.append("<col style=\"width:100px\">"); // 默认宽度为100px
                    break;
            }
        }
        htmlContent.append("</colgroup>");

        // 插入 caption(只读取第一行作为标题)
        if (firstRow != null) {
            htmlContent.append("<caption style=\"caption-side: top; font-size: 18px; font-weight: bold; margin-bottom: 10px;\">");
            for (Cell cell : firstRow) {
                htmlContent.append(cell.getStringCellValue()).append(" ");
            }
            htmlContent.append("</caption>");
        }

        // 遍历后续每一行(跳过第一行)
        boolean firstDataRow = true;
        for (Row row : sheet) {
            if (firstDataRow) {
                firstDataRow = false;
                continue; // 跳过第一行(已作为标题处理)
            }

            htmlContent.append("<tr style=\"border-bottom: 1px solid #ccc;\">");
            for (Cell cell : row) {
                htmlContent.append("<td style=\"border: 1px solid #ddd; padding: 8px; text-align: left;\">");
                switch (cell.getCellType()) {
                    case STRING:
                        htmlContent.append(cell.getStringCellValue());
                        break;
                    case NUMERIC:
                        if (DateUtil.isCellDateFormatted(cell)) {
                            htmlContent.append(cell.getDateCellValue());
                        } else {
                            htmlContent.append(cell.getNumericCellValue());
                        }
                        break;
                    case BOOLEAN:
                        htmlContent.append(cell.getBooleanCellValue());
                        break;
                    default:
                        htmlContent.append("&nbsp;");
                        break;
                }
                htmlContent.append("</td>");
            }
            htmlContent.append("</tr>");
        }

        htmlContent.append("</table></body></html>");

        workbook.close();
        fis.close();
        return htmlContent.toString();
    }

    public static String convertDocxToHtml(String docxFilePath,String localFilePrefix,String domain,String localFilePath){
        StringBuilder htmlContent = new StringBuilder("<html><body>");
        try (FileInputStream fis = new FileInputStream(docxFilePath);
             XWPFDocument document = new XWPFDocument(fis)) {
            // 遍历段落
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                for (XWPFRun run : paragraph.getRuns()) {
                    List<XWPFPicture> pictures = run.getEmbeddedPictures();
                    if (!pictures.isEmpty()) {
                        for (XWPFPicture picture : pictures) {
                            XWPFPictureData pictureData = picture.getPictureData();
                            byte[] imgBytes = pictureData.getData();

                            String baseDir = localFilePath;
                            String folderName = "temp";
                            Path folderPath = Paths.get(baseDir, folderName);

                            if (!Files.exists(folderPath)) {
                                Files.createDirectories(folderPath);
                            }

                            Path tempFile = Files.createTempFile(folderPath, "temp", ".png");
                            Files.write(tempFile, imgBytes);
                            String fileUrl = domain + localFilePrefix + "/temp/" + tempFile.getFileName().toString();
                            System.out.println("临时文件创建成功:" + tempFile.toAbsolutePath());

                            htmlContent.append("<img style=\"height: auto; width: auto;\" src='").append(fileUrl).append("'/>");
                        }
                    } else {
                        String s = run.toString();
                        String text = run.getText(0);
                        if (text != null) {
                            // 也可以考虑使用<p>标签来包裹每个run的内容,以保留原始格式
                            htmlContent.append("<p style=\"width: 1000px;word-break: break-all;\">").append(text).append("</p>");
                        } else {
                            htmlContent.append(""); // 避免 null 插入 HTML 内容
                        }
                    }
                }
            }

            htmlContent.append("</body></html>");
            System.out.println(htmlContent);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return htmlContent.toString();
    }
}

3,controller调用(中间依赖到了一个下载文件的逻辑,请自己补全)

/**
 * 文件请求处理
 *
 * @author ruoyi
 */
@RestController
public class SysFileController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;
    /**
     * 域名或本机访问地址
     */
    @Value("${file.domain}")
    public String domain;
    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;


    /**
     * 文件转html预览
     *
     * @param fileUrls 文件URL列表
     */
    @PostMapping("getFileHtml")
    public String getFileHtml(@RequestBody List<String> fileUrls) {
        String htmlString = "";
        try {

                for (String fileUrl : fileUrls) {
                    try {
                        // 从文件URL后缀名
                        String substring = fileUrl.substring(fileUrl.lastIndexOf('.') + 1);
                        System.out.println("substring:"+substring);
                        if (substring.equals("xlsx")){
                            // 从文件服务获取文件
                            byte[] fileData = sysFileService.downloadFile(fileUrl);
                            if (fileData != null) {
                                // 创建临时文件并写入文件字节
                                Path tempFile = Files.createTempFile("downloaded_", ".xlsx");
                                Files.write(tempFile, fileData);
                                htmlString = FileToHtmlUtils.convertExcelToHtml(tempFile.toString());
                            }
                        }else if (substring.equals("docx")){
                            // 从文件服务获取文件
                            byte[] fileData = sysFileService.downloadFile(fileUrl);
                            if (fileData != null) {
                                // 创建临时文件并写入文件字节
                                Path tempFile = Files.createTempFile("downloaded_", ".docx");
                                System.out.println("临时docx文件"+tempFile);
                                Files.write(tempFile, fileData);
                                htmlString = FileToHtmlUtils.convertDocxToHtml(tempFile.toString(),localFilePrefix,domain,localFilePath);
                            }
                        }


                    } catch (Exception e) {
                        log.error("下载文件失败: " + fileUrl, e);
                        // 继续处理下一个文件
                    }
                }
        } catch (Exception e) {
            log.error("批量下载文件失败", e);
            throw new RuntimeException("批量下载文件失败", e);
        }
        System.out.println(htmlString);
        return htmlString;

    }



}

vue测试页面

<template>
  <div>
    <div class="html-content" v-html="processedHtmlContent"></div>
    <div>
      <iframe
        :src="pdfUrl"
        frameborder="0"
        style="width: 50%; height: 800px"
      ></iframe>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rawHtmlContent: `<html><body><p style="width: 1000px;word-break: break-all;">良果多多的完美世界</p><img style="height: auto; width: auto;" src='http://127.0.0.1:8080/statics/temp/temp1275686831319271272.png'/><p style="width: 1000px;word-break: break-all;">2222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222</p><p style="width: 1000px;word-break: break-all;">33333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333</p><p style="width: 1000px;word-break: break-all;">4444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444</p><p style="width: 1000px;word-break: break-all;">5555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555</p><p style="width: 1000px;word-break: break-all;">666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666</p><p style="width: 1000px;word-break: break-all;">77777777777777777777777777777777777777777777777777777777777777777777777</p><p style="width: 1000px;word-break: break-all;">77777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777</p><p style="width: 1000px;word-break: break-all;">88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888</p><p style="width: 1000px;word-break: break-all;">9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999</p></body></html>`,
      processedHtmlContent: "",
      pdfUrl: 'http://127.0.0.1:8080/statics/temp/好果子中国造.pdf'
    };
  },
  mounted() {
    this.processedHtmlContent = this.rawHtmlContent;
  },
};
</script>

<style scoped>
.html-content img {
  max-width: 100%;
  height: auto;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值