在 Java 中讀取 Excel 文件(教程)
什麼是Excel?
Microsoft Excel工作簿是一個基於電子表格的軟體,允許使用者有效地組織和儲存資料。 它以表格形式儲存和組織資料,即使用行和列。 Excel電子表格中的儲存格是儲存資料並可以使用不同的樣式、格式和公式操作的方框。
如何在Java中讀取Excel文件?
有時候讀取Excel文件可能很複雜。 由於Excel的儲存格,在Java中讀取Excel文件與在Java中讀取Word文件略有不同。 JDK不提供直接的API來讀取或寫入Microsoft Excel文件。 相反,我們必須依賴第三方程式庫Apache POI。
Apache POI程式庫
POI代表"Poor Obfuscation Implementation"。 Apache POI是一個開源Java程式庫,設計用於讀取和寫入Microsoft文件。 它提供了一種建立和操作基於Microsoft Office的各種文件格式的方法。使用Apache POI,可以建立、修改和顯示/讀取Microsoft Office文件格式的範圍內的操作。
下載和安裝Apache POI程式庫
首先,我們將下載POI JAR的最新版本。 導航至http://poi.apache.org/download.html並下載最新的ZIP文件,這將包含在Java中讀取Excel文件的Java API。
下載Apache POI JAR文件
下載ZIP文件後,您需要解壓縮它,並將以下JAR文件新增到您項目的類路徑中。 這在下文的從Excel文件讀取中解釋。
將Apache POI Jar文件新增到Java的類路徑
注意:還要將ooxml-lib中的文件與其他文件一起複製。
POI中的類和介面
以下是支持XLS和XLSX文件格式的類,可以使用:
Apache POI類
以下是POI中不同Java介面和類的列表,用於在Java中讀取XLS和XLSX文件:
Workbook介面由XSSFWorkbook類實現:
- HSSFWorkbook:這是XLS文件的類表示。
- XSSFWorkbook:這是XLSX文件的類表示。
Sheet介面由XSSFSheet類實現:
- HSSFSheet:這是XLS文件中表的類表示。
- XSSFSheet:這是XLSX文件中表的類表示。
Row介面由XSSFRow類實現:
- HSSFRow:這是XLS文件的表的一行的類表示。
- XSSFRow:這是XLSX文件的表的一行的類表示。
Cell介面由XSSFCell類實現:
- HSSFCell:這是XLS文件的一行中的單元格的類表示。
- XSSFCell:這是XLSX文件的一行中的單元格的類表示。
從Excel文件讀取
我們的例子中,我們將在Java中讀取以下Excel文件:
將被讀取的Excel文件
在Java中讀取Excel文件的步驟
- 使用任何Java IDE建立一個Java項目。我們將使用Netbeans作為該項目。
- 接下來,在項目中建立一個
lib文件夾。 - 然後,將下載的JAR文件新增到在前一步中建立的
lib文件夾中。 - 右鍵單擊項目文件夾 > 構建路徑 > 新增外部JAR文件 > 選擇所有上述JAR文件 > 應用並關閉來設定
Class-Path。 - 現在,讓我們建立一個名為ReadExcelFileDemo的類文件。
- 建立一個名為"studentdata.xls"的Excel文件,將上述資料或任何資料寫入其中。
以下是用Java讀取Excel文件的程式碼範例:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
public class ReadExcelFileDemo {
public static void main(String[] args) throws IOException {
// Obtain input bytes from a file
FileInputStream fis = new FileInputStream(new File("C:\\demo\\studentdata.xls"));
// Creating workbook instance that refers to .xls file
HSSFWorkbook wb = new HSSFWorkbook(fis);
// Creating a Sheet object to retrieve the object
HSSFSheet sheet = wb.getSheetAt(0);
// Evaluating cell type
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
for (Row row : sheet) {
for (Cell cell : row) {
switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {
case NUMERIC: // Field that represents numeric cell type
// Getting the value of the cell as a number
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case STRING: // Field that represents string cell type
// Getting the value of the cell as a string
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println();
}
// Closing the workbook to free resources
wb.close();
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
public class ReadExcelFileDemo {
public static void main(String[] args) throws IOException {
// Obtain input bytes from a file
FileInputStream fis = new FileInputStream(new File("C:\\demo\\studentdata.xls"));
// Creating workbook instance that refers to .xls file
HSSFWorkbook wb = new HSSFWorkbook(fis);
// Creating a Sheet object to retrieve the object
HSSFSheet sheet = wb.getSheetAt(0);
// Evaluating cell type
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
for (Row row : sheet) {
for (Cell cell : row) {
switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {
case NUMERIC: // Field that represents numeric cell type
// Getting the value of the cell as a number
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case STRING: // Field that represents string cell type
// Getting the value of the cell as a string
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println();
}
// Closing the workbook to free resources
wb.close();
}
}
輸出:
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 Ahsan
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 Ahsan
讀取XLSX文件的步驟是相同的,除了以下兩個主要點:
- 首先,更改文件格式為.xlsx。 同一文件"studentdata"可以使用,但使用.xlsx擴展名。
- 第二,我們導入Java Apache POI的方式有所不同。 程式碼如下:
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class XLSXReaderExample {
public static void main(String[] args) {
try {
File file = new File("C:\\demo\\studentdata.xlsx");
FileInputStream fis = new FileInputStream(file);
// Creating Workbook instance that refers to .xlsx file
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
// Iterating over rows using iterator
Iterator<Row> itr = sheet.iterator();
while (itr.hasNext()) {
Row row = itr.next();
// Iterating over each column in a row
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case NUMERIC: // Field that represents numeric cell type
// Getting the value of the cell as a number
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case STRING: // Field that represents string cell type
// Getting the value of the cell as a string
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
// Closing the workbook to free resources
wb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class XLSXReaderExample {
public static void main(String[] args) {
try {
File file = new File("C:\\demo\\studentdata.xlsx");
FileInputStream fis = new FileInputStream(file);
// Creating Workbook instance that refers to .xlsx file
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
// Iterating over rows using iterator
Iterator<Row> itr = sheet.iterator();
while (itr.hasNext()) {
Row row = itr.next();
// Iterating over each column in a row
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case NUMERIC: // Field that represents numeric cell type
// Getting the value of the cell as a number
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case STRING: // Field that represents string cell type
// Getting the value of the cell as a string
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
// Closing the workbook to free resources
wb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
輸出:
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 Ahsan
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 Ahsan
IronXL C#程式庫
IronXL是一個獨立的.NET程式庫,方便使用C#讀取和編輯Microsoft Excel文件。 它既不要求安裝Microsoft Excel,也不依賴Interop。
使用IronXL,開發人員只需撰寫幾行程式碼即可輕鬆執行所有Excel相關計算,且性能快速。 這可以用於如將兩個儲存格相加、計算欄的總計、將整列新增到Excel表中、將整行新增到Excel表中、單行和多行列求和或通過IronXL的有用功能完成的許多其他任務。
IronXL完全支持.NET Framework、.NET Core、移動、Xamarin、Azure Linux和macOS。
IronXL功能集
- 從XLS/XLSX/CSV/TSV載入、讀取和編輯資料。
- 保存並匯出到XLS/XLSX/CSV/TSV/JSON。
System.Data物件 — 將Excel電子表格作為System.Data.DataSet和System.Data.DataTable物件使用。- 公式 — 與Excel公式配合使用。
- 範圍 — ["A1:B10"]語法易於使用。
- 排序 — 排序行、列和範圍。
- 樣式 — 視覺樣式、字體和字體大小、背景圖案、邊框、對齊方式和數字格式。
以下是使用IronXL在C#中讀取Excel文件的程式碼範例:
using IronXL;
using System.Linq;
public class ExcelReaderExample
{
public static void Main(string[] args)
{
// Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
// Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly
foreach (var cell in sheet["A2:A10"]) {
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
}
}
using IronXL;
using System.Linq;
public class ExcelReaderExample
{
public static void Main(string[] args)
{
// Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
// Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly
foreach (var cell in sheet["A2:A10"]) {
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
}
}
Imports IronXL
Imports System.Linq
Public Class ExcelReaderExample
Public Shared Sub Main(ByVal args() As String)
' Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
Dim sheet As WorkSheet = workbook.WorkSheets.First()
' Select cells easily in Excel notation and return the calculated value
Dim cellValue As Integer = sheet("A2").IntValue
' Read from Ranges of cells elegantly
For Each cell In sheet("A2:A10")
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell
End Sub
End Class
使用IronXL使開發人員的工作變得更加容易。 其簡單且易於使用的程式碼使軟體在處理Excel文件時更不易于出錯。
下載IronXL並立即在您的項目中使用。




