導(dǎo)入pom依賴
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
創(chuàng)建Excel文件
public static void setPoi() throws IOException {
//創(chuàng)建Excel表格
XSSFWorkbook sheets = new XSSFWorkbook();
//創(chuàng)建sheet
XSSFSheet sheet = sheets.createSheet("精神小伙");
// 表格得大小是*X*
sheet.setColumnWidth(10,51);
//創(chuàng)建第一行
XSSFRow row = sheet.createRow(0);
XSSFRow row6 = sheet.createRow(6);
//創(chuàng)建表頭
row.createCell(0).setCellValue("精神小伙");
row.createCell(1).setCellValue("不請自來");
row.createCell(2).setCellValue("滴~滴滴~");
//設(shè)置第二行
XSSFRow row1 = sheet.createRow(1);
//在第二行寫數(shù)據(jù) 這是第二行第一列的數(shù)據(jù)
row1.createCell(0).setCellValue("第二個(gè)精神小伙");
row1.createCell(1).setCellValue("第二個(gè)不請自來");
row1.createCell(2).setCellValue("滴~滴滴~");
//創(chuàng)建表格路徑
File file = new File("D:\\guoyang\\測試.xlsx");
FileOutputStream fileOutputStream = new FileOutputStream(file);
//寫入文件
sheets.write(fileOutputStream);
fileOutputStream.close();
}
獲取到Excel文件內(nèi)容
public static void import07() throws IOException {
File file = new File("D:\\guoyang\\測試.xlsx");
//獲得該文件的輸入流
FileInputStream stream = new FileInputStream(file);
// 多態(tài) 拋異常
Workbook sheets = new XSSFWorkbook(stream);
//獲取一個(gè)工作表(sheet頁),下標(biāo)從0開始
Sheet sheet = sheets.getSheetAt(0);
for (int i = 1; i<=sheet.getLastRowNum() ; i++) {
System.out.println(sheet.getLastRowNum());
// 獲取行數(shù)
Row row = sheet.getRow(i);
// 獲取單元格 取值
String value = row.getCell(0).getStringCellValue();
String value1 = row.getCell(1).getStringCellValue();
String value2 = row.getCell(2).getStringCellValue();
// 輸出
System.out.println(value);
System.out.println(value1);
System.out.println(value2);
}
//關(guān)流
sheets.close();
stream.close();
}
總之使用poi來進(jìn)行操作表格還是相對簡單的隆豹,更多功能需要親自體驗(yàn)北救。
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者