帮我写一个java解析excel
时间: 2023-07-07 17:05:32 浏览: 47
好的,下面是一个简单的Java程序,可以解析Excel文件:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
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 ExcelParser {
public static void main(String[] args) {
try {
// 创建文件对象
File excelFile = new File("test.xlsx");
// 创建 FileInputStream 对象
FileInputStream fis = new FileInputStream(excelFile);
// 创建 Workbook 对象
Workbook workbook = WorkbookFactory.create(fis);
// 获取第一个 Sheet
Sheet sheet = workbook.getSheetAt(0);
// 创建迭代器
Iterator<Row> rowIterator = sheet.iterator();
// 创建 ArrayList 用于存储数据
ArrayList<String[]> dataList = new ArrayList<String[]>();
// 遍历每一行
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
String[] rowData = new String[row.getLastCellNum()];
// 遍历每一列
for (int i = 0; i < row.getLastCellNum(); i++) {
Cell cell = row.getCell(i);
String cellValue = "";
// 判断单元格类型
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
cellValue = Double.toString(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = Boolean.toString(cell.getBooleanCellValue());
break;
}
}
rowData[i] = cellValue;
}
dataList.add(rowData);
}
// 打印数据
for (String[] row : dataList) {
for (String cell : row) {
System.out.print(cell + "\t");
}
System.out.println();
}
// 关闭文件流和工作簿
fis.close();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个程序使用了 Apache POI 库来操作 Excel 文件。你需要将 Excel 文件放在程序所在的目录下,并将文件名更新为正确的名称。