Excel模板下载\数据导出
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());
}
}