poi excel文档生成与读取
生活随笔
收集整理的這篇文章主要介紹了
poi excel文档生成与读取
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
阿帕奇poi excel文檔操作
- 1. introduce
- 2. 輪子
- 3. demo 以九九乘法表為例
- 3.1 xls的生成
- 3.2 xlsx的生成
- 3.3 讀取xlsx
1. introduce
poi是什么
答:用于excel的操作的,可以對集合,map進行操作生成對應的excel文檔。做報表。
對應的iText是pdf操作的
excel的兩種版本
區別:后綴名不同。某w*s就是03的。。
xls用老版本的excel和新版本的excel軟件都能打開。
而新版本的excel文件不會向下兼容。
2. 輪子
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.9</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.9</version></dependency>3. demo 以九九乘法表為例
3.1 xls的生成
/*** 給定excel文件名 和 excel文檔 生成excel文件* @param excelFileName* @param wb*/void createExcelFile(String excelFileName, Workbook wb) {// 生成文件,字節流輸出File file = new File(excelFileName);OutputStream out = null;try {out = new FileOutputStream(file);try {wb.write(out);} catch (IOException e) {e.printStackTrace();}} catch (FileNotFoundException e) {e.printStackTrace();} finally {if (out != null) {try {out.close();} catch (IOException e) {e.printStackTrace();}}}}@Test/*** 生成xls的excel文檔 97~03 年*/public void test2() {// 生成空白文檔HSSFWorkbook hssfWorkbook = new HSSFWorkbook();// 生成sheet頁HSSFSheet sheet1 = hssfWorkbook.createSheet("sheet page1");// 行for (int i = 0; i < 9; i++) {// 創建行HSSFRow row = sheet1.createRow(i);// 列for (int j = 0; j <= i; j++) {// 創建單元格HSSFCell cell = row.createCell(j);String res = (i + 1) + " * " + (j + 1) + " = " + (i + 1) * (j + 1);// 設置單元格內容cell.setCellValue(res);}}createExcelFile("excel1.xls", hssfWorkbook);}3.2 xlsx的生成
換了個api
/*** 生成xlsx 的文檔*/@Testpublic void test3() {// 空白文檔XSSFWorkbook xssfSheets = new XSSFWorkbook();// sheet頁1XSSFSheet sheet1 = xssfSheets.createSheet("sheet1");// 行for (int i = 0; i < 9; i++) {// 創建行XSSFRow row = sheet1.createRow(i);// 列for (int j = 0; j <= i; j++) {// 創建單元格XSSFCell cell = row.createCell(j);String res = (i + 1) + " * " + (j + 1) + " = " + (i + 1) * (j + 1);// 設置單元格內容cell.setCellValue(res);}}createExcelFile("excel2.xlsx", xssfSheets);}3.3 讀取xlsx
/*** 利用poi讀取xlsx文件*/@Testpublic void test4() {try {InputStream in = new FileInputStream(new File("excel2.xlsx"));// 獲得excel文檔try {XSSFWorkbook xfb = new XSSFWorkbook(in);// sheet 頁XSSFSheet sheet = xfb.getSheetAt(0);// 最大行的下標int lastRowNum = sheet.getLastRowNum();for (int i = 0; i < lastRowNum; i++) {// 拿到每行XSSFRow row = sheet.getRow(i);// 最大單元的行下標short cellNum = row.getLastCellNum();// 遍歷單元格for (int j = 0; j < cellNum; j++) {// 獲得單元格XSSFCell cell = row.getCell(j);if (cell != null)System.out.print(cell + " ");}System.out.println();}} catch (IOException e) {e.printStackTrace();}} catch (FileNotFoundException e) {e.printStackTrace();}}最后,輪子的都得是,會用改,然后會用就行。
總結
以上是生活随笔為你收集整理的poi excel文档生成与读取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 分布式下的session问题
- 下一篇: 内存一致性模型指南