java如何倒入excel
导入Excel文件的方法
在Java中导入Excel文件通常使用Apache POI库。Apache POI提供了对Microsoft Office格式文件的读写功能,包括Excel(.xls和.xlsx格式)。
添加依赖
在Maven项目中,添加以下依赖到pom.xml文件:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
读取Excel文件
以下代码示例展示了如何读取Excel文件内容:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class ExcelReader {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("example.xlsx");
Workbook workbook = new XSSFWorkbook(fis)) {
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();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
处理不同Excel格式
对于旧版Excel文件(.xls格式),使用HSSFWorkbook类:
Workbook workbook = new HSSFWorkbook(fis);
对于新版Excel文件(.xlsx格式),使用XSSFWorkbook类:
Workbook workbook = new XSSFWorkbook(fis);
高级读取选项
如果需要更精细地控制读取过程,可以使用DataFormatter来格式化单元格值:
DataFormatter formatter = new DataFormatter();
String cellValue = formatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
异常处理
确保正确处理可能出现的异常,如文件不存在或格式错误:

try {
// 读取Excel代码
} catch (IOException e) {
System.err.println("文件读取错误: " + e.getMessage());
} catch (InvalidFormatException e) {
System.err.println("文件格式错误: " + e.getMessage());
}






