實踐環(huán)境
Win10
Java JDK1.8
代碼實現(xiàn)
pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.shouke</groupId>
<artifactId>example</artifactId>
<version>1.0</version>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<poi.ooxml.version>4.1.2</poi.ooxml.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.ooxml.version}</version>
</dependency>
<dependencies>
</project>
讀取Excel
代碼實現(xiàn)
exmple.xml
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.util.Iterator;
public class JavaStudy {
public static void readExcel(String filePath) throws Exception {
//獲取文件流
FileInputStream inputStream = new FileInputStream(filePath);
//1.創(chuàng)建工作簿
Workbook workbook = new XSSFWorkbook(inputStream);
//2.得到Sheet表
// Sheet sheet = workbook.getSheet("Sheet1"); // 通過Sheet名稱獲取
Sheet sheet = workbook.getSheetAt(0); // 通過索引獲取 //獲取第1個Sheet表
//3.獲取行
Row row = sheet.getRow(0); // 獲取第1行 // 注意:行索引從0開始
System.out.println(sheet.getFirstRowNum()); // 獲取首行(內(nèi)容行)索引 // 輸出:0
System.out.println(sheet.getLastRowNum()); // 獲取最后行(內(nèi)容行)索引 // 輸出:5
//4.獲取單元格
Cell cell = row.getCell(0); // 獲取行的第0個元
//5.獲取單元格的值
System.out.println(getValue(cell)); // 輸出:姓名
System.out.println(row.getFirstCellNum()); // 獲取當前行第一個內(nèi)容單元格索引 // 輸出:0
System.out.println(row.getLastCellNum()); // 獲取當前行最后內(nèi)容單元格往后下一個單元格的索引 // 輸出:7 // 輸出值為:最后內(nèi)容單元格索引+1
// 遍歷當前行內(nèi)容化單元格
// 方法1:
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
System.out.println(cell);
}
// 方法2:
row.forEach(currCell -> {
System.out.print(currCell+", ");
System.out.println(currCell.getCellType());
});
// 遍歷獲取所有內(nèi)容行單元格的值
for (int rowIndex=0; rowIndex<=sheet.getLastRowNum(); rowIndex++) {
row = sheet.getRow(rowIndex);
for(int colIndex=0; colIndex<row.getLastCellNum(); colIndex++) {
System.out.println(getValue(row.getCell(colIndex)));
}
}
inputStream.close();
}
public static Object getValue(Cell cell) {
//匹配類型數(shù)據(jù)
Object cellValue = null;
if (cell != null) { // 單元格未經(jīng)過編輯的情況下,一定為null //cell為null的情況下,對空單元格調用API會導致上述for循環(huán)提前結束
CellType cellType = cell.getCellType(); // 獲取單元格數(shù)值類型
switch (cellType) {
case STRING: //字符串
System.out.print("String類型:");
cellValue = cell.getStringCellValue();
break;
case BOOLEAN: //布爾類型
System.out.print("Boolean類型:");
cellValue = cell.getBooleanCellValue();
break;
case BLANK: //空
System.out.print("BLANK類型:"); // 填寫值后,請清理掉值,從沒填過值,那么cell=null,合并的單元格被當做一個單元格
break;
case NUMERIC: //數(shù)字(整數(shù)、小數(shù)、日期)
System.out.print("NUMERIC類型:");
if (DateUtil.isCellDateFormatted(cell)) { //日期
System.out.print("日期:");
cellValue = cell.getDateCellValue(); // cell.getDateCellValue() 返回Date類型數(shù)據(jù)
} else {
System.out.print("數(shù)字:");
cellValue = cell.getNumericCellValue();
System.out.println(1.0E50 == (Double) cellValue);
}
break;
case FORMULA:
System.out.print("公式類型:");
cellValue = cell.getCellFormula();
break;
case ERROR:
System.out.print("數(shù)據(jù)類型錯誤");
break;
}
} else {
System.out.println("cell為空");
}
return cellValue;
}
// 測試
public static void main(String[] args) {
try{
JavaStudy.readExcel("D:\\codePojects\\Study\\src\\main\\resource\\example.xlsx");
} catch (Exception e) {
}
}
}
補充說明
創(chuàng)建工作簿
POI創(chuàng)建工作簿的API有3種:
-
HSSFWorkbook
: 此API用于操作Excel 2003及之前的版本(文件擴展名.xls
),優(yōu)點是導出速度快,缺點是導出的行數(shù)有局限性,最多為65535行,超出65536條后系統(tǒng)就會報錯。對內(nèi)存消耗比較大,容易造成內(nèi)存溢出(OOM)。 -
XSSFWorkbook
: 此API用于操作Excel 2007及往后的版本(文件擴展名.xlsx
),優(yōu)點是導出的數(shù)據(jù)行數(shù)突破65535,最大可導出1048576行,缺點導出速度慢,對內(nèi)存消耗比較大,容易造成內(nèi)存溢出(OOM)。 -
SXSSFWorkbook
:POI3.8開始,新增此API,是XSSFWorkbook
API的兼容流式擴展,主要解決當使用XSSFWorkbook
方式導出大數(shù)據(jù)量時,內(nèi)存溢出的問題,支持導出大量的數(shù)據(jù)。其原理就是使用硬盤空間代替內(nèi)存:僅保存最新的數(shù)據(jù)行在內(nèi)存里供查看,在此之前的數(shù)據(jù)行都會被寫入到硬盤里(Windows電腦的話,是寫入到C盤根目錄下的temp文件夾)。被寫入到硬盤里的數(shù)據(jù)行是不可見的/不可訪問的。只有還保存在內(nèi)存里的才可以被訪問到。
以XSSFWorkbook
API為例,可以通過多種方式來創(chuàng)建工作簿,常見用法如下:
//獲取文件流
FileInputStream inputStream = new FileInputStream(excelFilePath);
//創(chuàng)建工作簿
Workbook workbook = new XSSFWorkbook(inputStream);
// 或者
//創(chuàng)建文件
File file = new File(excelFilePath);
Workbook workbook = new XSSFWorkbook(file);
// 或者
Workbook workbook = new XSSFWorkbook(excelFilePath);
獲取單元格類型
CellType getCellType();
返回類型為CellType
,在org.apache.poi.ss.usermodel.CellType
中定義,它是一個枚舉類型,源碼如下:
public enum CellType {
@Internal(
since = "POI 3.15 beta 3"
)
_NONE(-1),
NUMERIC(0), // // 數(shù)字(整數(shù)、小數(shù)、日期)
STRING(1),
FORMULA(2), // 公式,即單元格內(nèi)容通過公式計算出來
BLANK(3), // 為空//什么時候會存儲空值,取決于所使用的表格軟件
BOOLEAN(4),
ERROR(5);
寫入Excel
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class JavaStudy {
public static void writeExcel(String filePath) throws IOException {
Workbook workbook = new XSSFWorkbook();
// Sheet sheet = workbook.createSheet();
Sheet sheet = workbook.createSheet("study"); // 創(chuàng)建Sheet時指定Sheet名詞
Row row = sheet.createRow(0); // 創(chuàng)建第1行
Cell firstCell = row.createCell(0); // 創(chuàng)建第1個單元格
firstCell.setCellValue("hello"); // 設置單元格的值
Cell secondCell = row.createCell(1); // 創(chuàng)建第2個單元格
secondCell.setCellValue("shouke");
row = sheet.createRow(1); // 創(chuàng)建第2行
firstCell = row.createCell(0, CellType.STRING); // 設置單元格的值和類型
firstCell.setCellValue("你好");
secondCell = row.createCell(1, CellType.NUMERIC); // 創(chuàng)建第2個單元格
secondCell.setCellValue(2023);
FileOutputStream fileOutputStream = new FileOutputStream(filePath); // 如果文件已存在,則覆蓋已有文件
workbook.write(fileOutputStream);
fileOutputStream.close();
workbook.close();
}
// 測試
public static void main(String[] args) {
try{
JavaStudy.writeExcel("D:\\codePojects\\Study\\src\\main\\resource\\result.xlsx");
} catch (Exception e) {
}
}
}
生成Excel文件內(nèi)容如下:文章來源:http://www.zghlxwxcb.cn/news/detail-616166.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-616166.html
到了這里,關于Java 基于Apache POI實現(xiàn)Excel讀寫操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!