java hutool poi 基于excel模板文件,填充数据的思路

需求

用户可下载excel模板文件,填充数据后上传,也可以下载已上传所有数据的excel,模板文件和含数据excel,都有列头及列说明;由此想到模板文件和含数据excel共用一份excel模板,下载数据时在模板文件上填充数据,填充完还不能影响模板文件。
hutool导出导入excel很方便,但没有依赖poi,需要手动添加poi依赖。

 <properties>
        <poi.version>4.1.2</poi.version>
        <hutool.version>5.5.9</hutool.version>
    </properties>
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>${hutool.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>${poi.version}</version>
</dependency>

解决思路

在内存中,将模板文件复制一份,不落到磁盘,然后填充数据,输出到response中。

// 通过工具类创建writer
import cn.hutool.core.io.FileUtil;
import org.apache.commons.io.FileUtils
// 通过工具类创建writer
String fileName = "数据模板.xlsx";
String destFilePath = “目标文件路径”;
File file = FileUtil.file(destFilePath );
try {
    FileUtils.copyFile(FileUtil.file(fileName), file);
} catch (IOException e) {
    log.warn("复制excel文件失败", e);
    throw new SystemException("复制excel文件失败");
}

ExcelWriter writer = ExcelUtil.getWriter(filePath);
response.setContentType("application/vnd.ms-excel");
try {
    response.setHeader("Content-disposition", "attachment; filename="
            + URLEncoder.encode(fileName, "utf8"));
} catch (UnsupportedEncodingException e) {
    log.warn("编码失败", e);
    throw new SystemException("编码失败");
}
//自定义标题别名
writer.addHeaderAlias("col1", "列1");
writer.addHeaderAlias("col2", "列2");
writer.addHeaderAlias("col3", "列3");

// 默认的,未添加alias的属性也会写出,如果想只写出加了别名的字段,可以调用此方法排除之
writer.setOnlyAlias(true);

// 一次性写出内容,使用默认样式,强制输出标题
writer.write(list, true);
// 关闭writer,释放内存
try {
    writer.flush(response.getOutputStream(), true);
} catch (IOException e) {
    log.warn("生成excel出错", e);
    throw new SystemException("导出excel出错");
} finally {
    writer.close();
    try {
        IoUtil.close(response.getOutputStream());
    } catch (IOException e) {
        log.warn("关闭servlet输出流失败", e);
    }
    file.delete();
}

猜你喜欢

转载自blog.csdn.net/wangjun5159/article/details/125554994
今日推荐