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

1.maven工程导入依赖

 
        org.apache.poi
        poi
        RELEASE
    
    
        org.apache.poi
        poi-ooxml
        RELEASE
    

这里导入两个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,自己稍微摸索一下就能够达到会用了,针对特殊需求自己在特殊解决吧。

你可能感兴趣的:(javaPOI)