java 读取的Excel文件
时间: 2023-10-23 12:14:13 浏览: 50
Java 读取 Excel 文件可以使用 Apache POI 库来实现。以下是一个简单的示例:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadExcel {
public static void main(String[] args) {
try {
// 创建文件对象
File file = new File("example.xlsx");
// 创建 FileInputStream 对象
FileInputStream fis = new FileInputStream(file);
// 创建 Workbook 对象
Workbook workbook = WorkbookFactory.create(fis);
// 获取第一个 Sheet
Sheet sheet = workbook.getSheetAt(0);
// 获取迭代器
Iterator<Row> rowIterator = sheet.iterator();
// 遍历所有行
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// 获取迭代器
Iterator<Cell> cellIterator = row.cellIterator();
// 遍历所有列
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// 根据单元格类型获取值
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
System.out.print("\t");
}
}
System.out.println();
}
// 关闭 Workbook 和 FileInputStream
workbook.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在代码中,我们使用了 FileInputStream 和 WorkbookFactory 类来读取 Excel 文件。然后,我们获取了第一个 Sheet,并使用迭代器遍历了所有行和所有列,最后根据单元格类型获取了值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)