jar 包地址:

  链接: https://pan.baidu.com/s/1gfOVslH 密码: 44wu

 

 1 /**
 2      * 创建一个工作薄
 3      * @throws IOException 
 4      */
 5     @Test
 6     public void createWorkbook() throws IOException {
 7         Workbook wb = new HSSFWorkbook() ;
 8         FileOutputStream out = new FileOutputStream("G:\\工作薄.xls") ;
 9         wb.write(out);
10         out.close();
11     }

 

 1 /**
 2      * 创建一个Sheet页
 3      * @throws IOException 
 4      */
 5     @Test
 6     public void createSheet() throws IOException {
 7         Workbook wb = new HSSFWorkbook() ;
 8         FileOutputStream out = new FileOutputStream("G:\\工作薄.xls") ;
 9         wb.createSheet("第一个Sheet页") ;
10         wb.createSheet("第二个Sheet页") ;
11         wb.write(out);
12         out.close();
13     }

 

 1 /**
 2      * 创建Row(行) 和 Cell(列) 并在单元格中写入数据
 3      * @throws IOException 
 4      */
 5     @Test
 6     public void createRowAndCell() throws IOException {
 7         Workbook wb = new HSSFWorkbook() ;
 8         FileOutputStream out = new FileOutputStream("G:\\工作薄.xls") ;
 9         Sheet oneSheet = wb.createSheet("第一个Sheet页") ;
10         
11         // 创建Row 
12         Row oneRow = oneSheet.createRow(0) ; // 创建第一行,可以创建多行
13         
14         // 创建Cell 
15         Cell oneCell = oneRow.createCell(0) ; // 创建第一列,也就是第一行的第一个单元格
16         Cell twoCell = oneRow.createCell(1) ; // 创建第二列,也就是第一行的第二个单元格
17         Cell threeCell = oneRow.createCell(2) ; 
18         Cell fourCell = oneRow.createCell(3) ; 
19         Cell fiveCell = oneRow.createCell(4) ;
20         Cell sixCell = oneRow.createCell(5) ;
21         
22         // 向单元格中写入数据
23         oneCell.setCellValue(true) ; // boolean 类型
24         twoCell.setCellValue(1) ;    // int 类型
25         fourCell.setCellValue(3.14D) ; // Double 类型
26         threeCell.setCellValue("Hello POI") ; // String 类型
27         sixCell.setCellValue(HSSFCell.CELL_TYPE_NUMERIC); // 可以写一些常量
28         
29         // 创建样式类,格式化时间
30         CellStyle cellStyle = wb.createCellStyle() ;
31         CreationHelper ch = wb.getCreationHelper() ;
32         cellStyle.setDataFormat(ch.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
33         fiveCell.setCellValue(new Date()) ; // Date 类型
34         fiveCell.setCellStyle(cellStyle);
35         
36         wb.write(out);
37         out.close();
38     }