Excel模板下载\数据导出

这篇博客介绍了如何在Spring Boot应用中利用Apache POI库读取和修改xlsx模板文件,然后将其导出为下载。文章详细展示了如何配置Maven依赖,设置资源打包规则,以及在Controller层实现Excel模板的下载功能。
摘要由CSDN通过智能技术生成

pom

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>


<build>
	<resources>
        <resource><!--将xlsx打包到jar-->
            <directory>src/main/resources</directory>
            <filtering>false</filtering>
            <includes>
                <include>**/*.xlsx</include>
            </includes>
        </resource>
        <resource><!--将除了xlsx以外的文件打包到jar-->
            <directory>src/main/resources</directory>
            <filtering>true</filtering><!--启用过滤器,使用pom.xml文件中<properties>标签定义的值替换${xxx}的值,如果没找到对应的<properties>属性,则${xxx}不会替换-->
            <excludes>
                <exclude>**/*.xlsx</exclude>
            </excludes>
        </resource>
    </resources>
    <!--添加resource配置可能导致src/main/java中的资源文件打包出现问题,解决思路见`日常随笔-springboot-SpringBoot解决mapper.xml存放在resources以外路径中的读取问题`-->
</build>

controller

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.ByteArrayOutputStream;


@RequestMapping(path = "/M/import/template", method = RequestMethod.GET)
@ApiOperation("下载导入模板")
@ApiImplicitParams({})
@ApiSecurity(accessType = ApiSecurity.AccessType.LOGIN)
public ResponseEntity<byte[]> exportBehaviorRecordExcelTemplate() throws MoralException {
    try {

        /** ============构造excel模板=========== **/

        Workbook wb = new XSSFWorkbook(Thread.currentThread().getContextClassLoader().getResourceAsStream("comment-import-template.xlsx"));//comment-import-template.xlsx文件放在src/main/resources中。

        //填数据
        Sheet sheetAt = wb.getSheetAt(0);
        //构造内容
        for (int i = 0;i < 10;i++) {
            Row row = sheetAt.createRow(i+1);
            row.createCell(0).setCellValue("第一列" + i);
            row.createCell(1).setCellValue("第二列" + i);
            row.createCell(2).setCellValue("第三列" + i);
        }
        //end
        
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        wb.write(bOut);
        byte[] byteArray = bOut.toByteArray();

        /** ========转换成流下载========= **/
        BodyBuilder builder = ResponseEntity.ok();
        builder.contentLength(byteArray.length);
        builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
        String filename = URLEncoder.encode("template.xlsx", "UTF-8");
        builder.header("Content-Disposition", "attachment; filename=" + filename);
        return builder.body(byteArray);

    } catch (Exception e) {
        throw new Exception("导出异常:" + e.getMessage());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值