POI介紹 ?
Apache POI是用Java編寫的免費開源的跨平臺的Java API,
Apache POI提供API給Java程序?qū)icrosoft Office格式檔案讀和寫的功能,
其中使用最多的就是使用POI操作Excel文件。
maven坐標:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
POI結(jié)構(gòu): ?文章來源:http://www.zghlxwxcb.cn/news/detail-709175.html
HSSF - 提供讀寫Microsoft Excel XLS格式檔案的功能
XSSF - 提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能
HWPF - 提供讀寫Microsoft Word DOC格式檔案的功能
HSLF - 提供讀寫Microsoft PowerPoint格式檔案的功能
HDGF - 提供讀Microsoft Visio格式檔案的功能
HPBF - 提供讀Microsoft Publisher格式檔案的功能
HSMF - 提供讀Microsoft Outlook格式檔案的功能
入門案例
從Excel文件讀取數(shù)據(jù)
使用POI可以從一個已經(jīng)存在的Excel文件中讀取數(shù)據(jù)文章來源地址http://www.zghlxwxcb.cn/news/detail-709175.html
public class POITest {
//使用POI讀取Excel中的數(shù)據(jù)
@Test
public void test1() throws Exception {
//加載指定文件,創(chuàng)建一個Excel(工作簿)
XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File("C:\\poitest.xlsx")));
//讀取Excel文件中第一個sheet標簽項
XSSFSheet sheet = excel.getSheetAt(0);
//遍歷sheet標簽項,獲取每一行數(shù)據(jù)
for (Row row : sheet) {
//遍歷行,獲取每個單元對象
for (Cell cell : row) {
System.out.println(cell.getStringCellValue());
}
}
//關(guān)閉資源
excel.close();
}
@Test
public void test2() throws Exception {
//加載指定文件,創(chuàng)建一個Excel(工作簿)
XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File("C:\\poitest.xlsx")));
//讀取Excel文件中第一個sheet標簽項
XSSFSheet sheet = excel.getSheetAt(0);
//獲取當前工作表最后一行的行號,行號從0開始
int lastRowNum = sheet.getLastRowNum();
for(int i=0;i<=lastRowNum;i++){
//根據(jù)行號獲取行對象
XSSFRow row = sheet.getRow(i);
//獲取當前行的最后一個單元格索引
short lastCellNum = row.getLastCellNum();
for(short j=0;j<lastCellNum;j++){
//根據(jù)單元格索引獲得單元格對象
XSSFCell cell = row.getCell(j);
System.out.println(cell.getStringCellValue());
}
}
//關(guān)閉資源
excel.close();
}
}
XSSFWorkbook:工作簿
XSSFSheet:工作表
Row:行
Cell:單元格
向Excel文件寫入數(shù)據(jù)
public class POITest {
//使用POI向Excel文件寫入數(shù)據(jù),并且通過輸出流將創(chuàng)建的Excel文件保存到本地磁盤
@Test
public void test3() throws Exception{
//在內(nèi)存中創(chuàng)建一個Excel文件(工作簿)
XSSFWorkbook excel = new XSSFWorkbook();
//創(chuàng)建一個工作表對象
XSSFSheet sheet = excel.createSheet("POI寫入數(shù)據(jù)");
//在工作表中創(chuàng)建行對象
XSSFRow title = sheet.createRow(0);
//在行中創(chuàng)建單元格對象
title.createCell(0).setCellValue("姓名");
title.createCell(1).setCellValue("地址");
title.createCell(2).setCellValue("年齡");
XSSFRow dataRow = sheet.createRow(1);
//在行中創(chuàng)建單元格對象
dataRow.createCell(0).setCellValue("小明");
dataRow.createCell(1).setCellValue("廣州");
dataRow.createCell(2).setCellValue("20");
//創(chuàng)建一個輸出流,通過輸出流將內(nèi)存中的Excel文件寫入本地磁盤
FileOutputStream outputStream = new FileOutputStream("C:\\hello1.xlsx");
excel.write(outputStream);
outputStream.flush();
excel.close();
}
}
到了這里,關(guān)于Apache POI的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!