我正在制作一个 spring boot 应用程序,它将获取 excel 文件并存储其内容并将其存储在数据库中。我尝试了很多方法..但没有成功。有没有人知道如何做到这一点。我不知道如何制作用于导入 excel 文件的控制器。为了从 excel 文件中读取数据,我必须包含任何依赖项吗?
原文由 Manish Bansal 发布,翻译遵循 CC BY-SA 4.0 许可协议
我正在制作一个 spring boot 应用程序,它将获取 excel 文件并存储其内容并将其存储在数据库中。我尝试了很多方法..但没有成功。有没有人知道如何做到这一点。我不知道如何制作用于导入 excel 文件的控制器。为了从 excel 文件中读取数据,我必须包含任何依赖项吗?
原文由 Manish Bansal 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 Apache POI 库,它可以通过 Maven Dependencies 轻松获得。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
读取文件的代码
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
public class ApachePOIExcelRead {
private static final String FILE_NAME = "/tmp/MyFirstExcel.xlsx";
public static void main(String[] args) {
try {
FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
//getCellTypeEnum shown as deprecated for version 3.15
//getCellTypeEnum ill be renamed to getCellType starting from version 4.0
if (currentCell.getCellTypeEnum() == CellType.STRING) {
System.out.print(currentCell.getStringCellValue() + "--");
} else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
System.out.print(currentCell.getNumericCellValue() + "--");
}
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
请根据您的要求修改以上程序。如果您知道您的 Excel 文件列索引,那么您可以直接读取单元格,例如 row.getCell(0)
其中 row
像 XSSFRow row = (XSSFRow) iterator.next();
这样的对象
希望这会帮助你
原文由 Rahul Mahadik 发布,翻译遵循 CC BY-SA 4.0 许可协议
15 回答8.3k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答6k 阅读
3 回答4k 阅读
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
终于找到了解决办法。
用于上传表单的 Html 文件是
控制器类是
确保添加依赖项
现在它会工作正常。