You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将带HTML标签的字符串解析为格式化字符串并通过EasyExcel导出至Excel

实现步骤

1. 解析HTML标签为带换行的纯文本

首先需要把带HTML标签的转义字符串转换成纯文本,并且将<p>标签对应为换行符。用Jsoup处理HTML解析是最便捷的方式,它能轻松提取文本并处理标签结构。

引入Jsoup依赖

在pom.xml中添加依赖:

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.17.2</version>
</dependency>

编写解析工具方法

创建工具类处理转义字符和HTML解析,精准提取段落内容并拼接换行:

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class HtmlTextUtils {
    public static String parseHtmlToPlainText(String htmlStr) {
        // 先处理转义引号,将&quot;替换为正常引号
        String unescapedStr = htmlStr.replace("&quot;", "\"");
        // 解析HTML文档
        Document doc = Jsoup.parse(unescapedStr);
        
        StringBuilder sb = new StringBuilder();
        // 遍历所有p标签,提取文本后用换行拼接
        doc.select("p").forEach(p -> {
            String text = p.text().trim();
            if (!text.isEmpty()) {
                if (sb.length() > 0) {
                    sb.append("\n");
                }
                sb.append(text);
            }
        });
        return sb.toString();
    }
}

测试示例:

String htmlStr = "&quot;<p>Hello</p><p>Good afternoon</p>&quot;";
String result = HtmlTextUtils.parseHtmlToPlainText(htmlStr);
// 输出结果:
// Hello
// Good afternoon

2. EasyExcel导出时保留换行格式

Excel默认不会识别文本中的\n换行,必须设置单元格自动换行样式,同时确保内容中的换行符为\n(Excel支持该标记)。

编写EasyExcel自动换行样式

创建样式工具类,配置单元格自动换行:

import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;

public class ExcelStyleUtils {
    public static HorizontalCellStyleStrategy getAutoWrapStyle() {
        // 表头样式(可根据需求调整)
        WriteCellStyle headStyle = new WriteCellStyle();
        headStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        
        // 内容样式:开启自动换行,设置对齐方式
        WriteCellStyle contentStyle = new WriteCellStyle();
        contentStyle.setWrapped(true); // 核心:开启自动换行
        contentStyle.setVerticalAlignment(VerticalAlignment.TOP);
        contentStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
        
        return new HorizontalCellStyleStrategy(headStyle, contentStyle);
    }
}

编写导出逻辑

定义导出实体类:

import com.alibaba.excel.annotation.ExcelProperty;

public class ExportData {
    @ExcelProperty(value = "内容", index = 0)
    private String content;

    // 构造方法、getter、setter省略
    public ExportData(String content) {
        this.content = content;
    }
}

编写导出接口:

import com.alibaba.excel.EasyExcel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
public class ExportController {

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 1. 处理HTML字符串为带换行的纯文本
        String htmlStr = "&quot;<p>Hello</p><p>Good afternoon</p>&quot;";
        String plainText = HtmlTextUtils.parseHtmlToPlainText(htmlStr);
        
        // 2. 构造导出数据
        List<ExportData> dataList = new ArrayList<>();
        dataList.add(new ExportData(plainText));
        
        // 3. 设置响应头,避免文件名乱码
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("内容导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        
        // 4. 导出Excel,应用自动换行样式
        EasyExcel.write(response.getOutputStream(), ExportData.class)
                .registerWriteHandler(ExcelStyleUtils.getAutoWrapStyle())
                .sheet("Sheet1")
                .doWrite(dataList);
    }
}

关键注意点

  • 解析HTML时,遍历<p>标签提取文本比直接取全文本更精准,能避免无关空格干扰。
  • EasyExcel必须开启setWrapped(true),否则Excel不会对\n做换行处理。
  • 导出时务必处理文件名的URL编码,避免中文文件名乱码。

内容的提问来源于stack exchange,提问作者郭乐源

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 13:25:10