把Excel导入到Java
时间: 2024-04-08 10:09:30 浏览: 9
要将Excel数据导入到Java中,你需要使用一个Java Excel库,比如Apache POI。下面是一个简单的代码示例:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
public static void main(String[] args) throws IOException {
FileInputStream inputStream = new FileInputStream(new File("data.xlsx"));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
}
}
System.out.println();
}
workbook.close();
inputStream.close();
}
}
```
这个代码片段读取名为“data.xlsx”的Excel文件,并逐行打印出每个单元格的值。你可以根据自己的需求修改该代码,以便将Excel数据导入到Java中。