java读取excel表格
时间: 2023-09-10 08:10:56 浏览: 168
Java读取Excel表格可以使用Apache POI库,该库提供了一些类和方法来操作Excel文件。下面是一个简单的例子:
1. 首先需要下载并添加Apache POI的依赖包到项目中。
2. 读取Excel文件,可以使用Workbook类和Sheet类。Workbook类代表整个Excel文件,Sheet类代表一个工作表。
```
FileInputStream file = new FileInputStream(new File("path/to/excel/file.xlsx"));
Workbook workbook = new XSSFWorkbook(file); // 根据文件类型创建Workbook对象
Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
```
3. 遍历工作表中的每一行和每一列,可以使用Row类和Cell类。
```
for (Row row : sheet) { // 遍历每一行
for (Cell cell : row) { // 遍历每一列
// 获取单元格的值
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();
}
```
完整的代码示例:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
public static void main(String[] args) throws IOException {
FileInputStream file = new FileInputStream(new File("path/to/excel/file.xlsx"));
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
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.close();
file.close();
}
}
```
注意:如果是读取xls格式的文件,需要使用HSSFWorkbook类代替XSSFWorkbook类。
阅读全文
相关推荐














