文件的导入导出一直用公司封装好的参数,后来自己写了单体应用,涉及到这块功能就自己学习了下,涉及不多,功能可以用。
引入依赖
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.3.0</version>
<dependency>
加工内容
创建对象:封装对应的标题
//创建对象
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
//创建sheet页
HSSFSheet sheet = wb.createSheet("XXX");
//创建样式
HSSFCellStyle style = wb.createCellStyle();
//标题
HSSFRow row1 = sheet.createRow(0);
//内容
HSSFCell cell = null;
String[] title = {"标题1", "标题2", "标题3", "标题4", "标题5", "标题6"};
for (int i = 0; i < title.length; i++) {
sheet.setColumnWidth(i, 15 * 256);//设置宽度,以256为单位
cell = row1.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
填充对应的参数:
首先加工要填充的数据:
String[][] content = new String[list.size()][6];
for (int i = 0; i < modelList.size(); i++) {
content[i][0] = "1";
content[i][1] = "2";
content[i][2] = "3";
content[i][3] = "4";
content[i][4] = "5";
content[i][5] = "6";
}
创建每行内容并填充:
/**
* 创建内容
*/
public void makeContent(HSSFSheet sheet, String[][] content) {
for (int i = 0; i < content.length; i++) {
HSSFRow row = sheet.createRow(i + 1);
for (int j = 0; j < content[i].length; j++) {
//将内容按顺序赋给对应的列对象
row.createCell(j).setCellValue(content[i][j]);
}
}
}
依次填充完每个sheet页后返回前端:
try {
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
OutputStream os = response.getOutputStream();
hssfWorkbook.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
结尾:
如果用postman自测的话,会显示乱码,点击save and download就可以保存文件,查看结果了。