生成java代码导入excel表格
时间: 2023-11-29 16:04:30 浏览: 49
以下是生成java代码导入excel表格的示例代码:
```
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.CellType;
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 ExcelImporter {
public static void main(String[] args) throws IOException {
// 读取Excel文件
File file = new File("data.xlsx");
FileInputStream inputStream = new FileInputStream(file);
Workbook workbook = new XSSFWorkbook(inputStream);
// 选择第一个工作表
Sheet sheet = workbook.getSheetAt(0);
// 遍历每一行
Iterator<Row> iterator = sheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
// 读取每个单元格的值
Iterator<Cell> cellIterator = currentRow.iterator();
ArrayList<String> rowData = new ArrayList<>();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
if (currentCell.getCellType() == CellType.STRING) {
rowData.add(currentCell.getStringCellValue());
} else if (currentCell.getCellType() == CellType.NUMERIC) {
rowData.add(String.valueOf(currentCell.getNumericCellValue()));
}
}
// 在这里你可以将rowData插入到数据库中,或者进行其他操作
System.out.println(rowData);
}
// 关闭文件输入流
inputStream.close();
}
}
```
这个示例代码使用了Apache POI库来读取Excel文件,并使用ArrayList来存储每一行的数据。在处理完每一行数据后,你可以将rowData插入到数据库中,或者进行其他操作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)