Java關於資料表poi操作
阿新 • • 發佈:2020-08-19
匯入pom依賴
<!-- 匯入依賴--> <!-- xls 03--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <!-- xls 07--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <!-- 日期格式化工具--> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.9.9</version> </dependency> <!-- test--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> </dependency>
建立個檔案測試一下
public class ExcelUtil { String PATH = "D:\\JavaClass\\mydemo\\src"; @Test public void testWrte() throws IOException { // 建立一個工作簿 // Workbook workbook = new HSSFWorkbook(); // 03 Workbook workbook = new XSSFWorkbook(); // 07 // 建立一個工作表 Sheet sheet = workbook.createSheet("統計表");// 建立一行 Row row1 = sheet.createRow(0); // 建立一個單元格 Cell cell1 = row1.createCell(0); // 填入資料 cell1.setCellValue("新增666"); // 2 ,1 Row row2 = sheet.createRow(1); Cell cell2 = row2.createCell(0); String s = new DateTime().toString("yyyy-MM-dd HH:mm:ss"); cell2.setCellValue(s);// 生成一張表 FileOutputStream fileOutputStream = null; fileOutputStream = new FileOutputStream(PATH + "單元測試.xls"); workbook.write(fileOutputStream); // 關閉流 fileOutputStream.close(); System.out.println("生成完成"); } }
執行檔案發現專案的根目錄下會出現一個單元測試.xls的檔案
讀取xls檔案的資料
@Test public void testRead() throws IOException{ // 讀表資料 FileInputStream inputStream = new FileInputStream(PATH + "單元測試.xls"); Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.getSheet("統計表"); Row row = sheet.getRow(0); Cell cell = row.getCell(0); System.out.println(cell.getStringCellValue()); inputStream.close(); }