alibaba / easyexcel

快速、简洁、解决大文件内存溢出的java处理Excel工具
https://easyexcel.opensource.alibaba.com
Apache License 2.0
31.52k stars 7.45k forks source link

建议增加HTML转EXCEl,可以参考EasyPOI #2732

Open songlipeng2003 opened 1 year ago

songlipeng2003 commented 1 year ago

目前的模板渲染还非常有限,稍微复杂一些的就无法支持,而且用起来很蹩脚,建议增加支持HTML转Excel。

ljluestc commented 1 month ago

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;

import java.io.FileOutputStream;
import java.io.IOException;

public class HtmlToExcelConverter {

    public static void main(String[] args) {
        // HTML内容
        String htmlContent = "<table>" +
                                "<tr><td>Hello</td><td>World</td></tr>" +
                                "<tr><td colspan=\"2\">This is a merged cell</td></tr>" +
                             "</table>";

        // 创建一个工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建一个工作表
        Sheet sheet = workbook.createSheet("Sheet1");

        // 使用Jsoup解析HTML内容
        Document doc = Jsoup.parse(htmlContent);
        Elements tables = doc.select("table");

        for (Element table : tables) {
            // 获取表格中的行
            Elements rows = table.select("tr");
            int rowNum = 0;
            for (Element row : rows) {
                // 创建Excel行
                Row excelRow = sheet.createRow(rowNum++);
                // 获取行中的单元格
                Elements cols = row.select("td");
                int colNum = 0;
                for (Element col : cols) {
                    // 创建Excel单元格
                    Cell excelCell = excelRow.createCell(colNum++);
                    // 设置单元格类型为字符串
                    excelCell.setCellType(CellType.STRING);
                    // 设置单元格内容
                    excelCell.setCellValue(col.text());
                }
            }
        }

        // 将工作簿写入文件
        try (FileOutputStream outputStream = new FileOutputStream("output.xlsx")) {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}