java解析Excel


FileInputStream fis = new FileInputStream("K:/1.xls");
POIFSFileSystem poi = new POIFSFileSystem(fis);
HSSFWorkbook hw = new HSSFWorkbook(poi);
HSSFSheet sheet = hw.getSheetAt(0);
for(int i=0;i<sheet.getPhysicalNumberOfRows();i++){
HSSFRow row = sheet.getRow(i);
HSSFCell cell = row.getCell((short)0);
System.out.print(cell+",");
cell = row.getCell((short)1);
System.out.println(cell+",");
}

### 使用Java解析Excel文件 为了处理Excel文件,在Java中有多个库可供选择,其中最常用的是Apache POI。此库支持读取和写入Microsoft Office文档,特别是Excel工作簿。 #### 添加依赖项 当使用Maven项目时,可以在`pom.xml`中添加如下依赖来引入Apache POI: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.3</version> </dependency> <!-- 如果需要操作.xlsx格式 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.3</version> </dependency> ``` 对于非Maven项目,则需下载JAR包并将其加入到项目的CLASSPATH中[^1]。 #### 解析Excel文件示例代码 下面是一个简单的例子展示如何利用Apache POI读取`.xlsx`类型的Excel文件中的数据: ```java 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) throws IOException { String path = "example.xlsx"; try (FileInputStream fis = new FileInputStream(path); 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: if (DateUtil.isCellDateFormatted(cell)) System.out.print(cell.getDateCellValue() + "\t"); else System.out.print(cell.getNumericCellValue() + "\t"); break; default: System.out.print("\t"); break; } } System.out.println(); } } } } ``` 这段程序会打开指定路径下的Excel文件,并打印出首张表格里的所有单元格的内容。注意这里只展示了基本功能;实际应用可能还需要考虑更多细节,比如错误处理、样式提取等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值