您的位置:首页 > 编程语言 > Java开发

springboot中使用java操作poi案例(excel数据写入与导出)

2019-06-12 20:59 781 查看

1.maven工程导入依赖

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

这里导入两个poi的原因是:在excel的表格保存为xls和xlsx两种格式,excel表格早先是xls后来又加入了xlsx的格式,在下面的代码中会有所体现。
2.编写demo

@RestController
@RequestMapping("/POI")
public class POIController {
@RequestMapping("/createExcel")
public void createExcel(HttpServletRequest request, HttpServletResponse response){
//HSSFWorkbook wb = new HSSFWorkbook();
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheets= wb.createSheet("九九乘法表");
for (int i=1;i<=9;i++){
XSSFRow row = sheets.createRow(i - 1);
for (int j = 1; j<= 9; j++) {
XSSFCell cell = row.createCell(j - 1);
cell.setCellValue(i+"*"+j+"="+i*j);
}

}

/*  try {
FileOutputStream fileOutputStream = new FileOutputStream("d:\\test.xlsx");
try {
wb.write(fileOutputStream);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}*/
try {
// 一个流两个头
//            两个头:1.文件的打开方式 默认是 inline(浏览器直接打开) 我们需要的是以附件方式下载 attachment
//                   2.文件的mime类型  常见的文件类型可以不写 word Excel TXT
String newExcel="aaa";
ServletOutputStream outputStream= response.getOutputStream();

response.setHeader("Content-Disposition", "attachment; filename="+newExcel+".xls");
wb.write(outputStream);
outputStream.close();
wb.close();
} catch (IOException e) {
e.printStackTrace();
}

}

直接复制粘贴就完事了,这里注意的点是在上图创建excel工作簿的时候有两种方式,如下所示:

HSSFWorkbook wb = new HSSFWorkbook();//生成xls格式的excel
XSSFWorkbook wb = new XSSFWorkbook();//生成xlsx格式的excel`

3.poi的整个设计是根据excel表格的特性来做的,大致思路是:

3.1通过
HSSFWorkbook wb = new HSSFWorkbook()或 XSSFWorkbook wb = new XSSFWorkbook()生成excel工作簿(wb)
3.2通过创建好的工作簿去创建工作表(sheet)
3.3通过工作表去创建表中的行(row),行里索要填的内容就是单元格的内容(cell)
最后,提供了工作簿(wb)、工作表(sheet)、表中的行(row)、行内容的单元格(cell)分别的api,自己稍微摸索一下就能够达到会用了,针对特殊需求自己在特殊解决吧。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: