alibaba / easyexcel

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

EasyExcel支持导出文件到表格吗?比如pdf、zip等文件。目前看样例中只有导出图片示例。 #3562

Open mathlpz opened 11 months ago

mathlpz commented 11 months ago

问题描述

请教下,EasyExcel支持导出文件到表格吗?比如pdf、zip等文件。 目前看样例中只有导出图片示例:https://easyexcel.opensource.alibaba.com/docs/current/quickstart/write#%E5%9B%BE%E7%89%87%E5%AF%BC%E5%87%BA

ljluestc commented 4 months ago
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.Data;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Data
class User {
    @ExcelProperty("ID")
    private Long id;

    @ExcelProperty("姓名")
    private String name;

    @ExcelProperty("年龄")
    private Integer age;
}

public class ExportExample {
    public static void main(String[] args) throws IOException, DocumentException {
        String excelFileName = "users.xlsx";
        String pdfFileName = "users.pdf";
        String zipFileName = "files.zip";

        // Step 1: 生成 Excel 文件
        List<User> users = new ArrayList<>();
        users.add(new User(1L, "Alice", 30));
        users.add(new User(2L, "Bob", 25));

        EasyExcel.write(excelFileName, User.class).sheet("用户数据").doWrite(users);

        // Step 2: 将 Excel 转换为 PDF
        try (FileInputStream excelFile = new FileInputStream(excelFileName);
             Workbook workbook = new XSSFWorkbook(excelFile);
             Document pdfDoc = new Document()) {

            Sheet sheet = workbook.getSheetAt(0);
            PdfWriter.getInstance(pdfDoc, new FileOutputStream(pdfFileName));
            pdfDoc.open();
            PdfPTable table = new PdfPTable(sheet.getRow(0).getLastCellNum());

            for (Row row : sheet) {
                for (Cell cell : row) {
                    table.addCell(cell.toString());
                }
            }

            pdfDoc.add(table);
        }

        // Step 3: 将文件打包为 ZIP
        try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFileName))) {
            for (String filePath : new String[]{excelFileName, pdfFileName}) {
                File fileToZip = new File(filePath);
                try (FileInputStream fis = new FileInputStream(fileToZip)) {
                    ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
                    zipOut.putNextEntry(zipEntry);

                    byte[] bytes = new byte[1024];
                    int length;
                    while ((length = fis.read(bytes)) >= 0) {
                        zipOut.write(bytes, 0, length);
                    }
                }
            }
        }
    }
}