栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

需求

用户可下载excel模板文件,填充数据后上传,也可以下载已上传所有数据的excel,模板文件和含数据excel,都有列头及列说明;由此想到模板文件和含数据excel共用一份excel模板,下载数据时在模板文件上填充数据,填充完还不能影响模板文件。

解决思路

在内存中,将模板文件复制一份,不落到磁盘,然后填充数据,输出到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();
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1003064.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号