gpt4 book ai didi

java - 将上传的excel存入数据库

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:24:02 26 4
gpt4 key购买 nike

我有一个代码,我的客户端可以将 excel 文件发送到服务器。服务器(SpringBoot)需要将 MultiplartFile“翻译”为 excel 文件。从那时起,数据需要被插入到数据库中。

但是,我从来不需要生成 excel,而是应该将电子表格中的数据直接插入到数据库中。

我首先尝试了:

@RequestMapping(value = "/insert", method = RequestMethod.POST, consumes = "multipart/form-data")
@ResponseBody
public MyMessage insertExcell(@RequestPart("typeFile") String typeFile,
@RequestPart("uploadFile") MultipartFile multipart, @RequestPart("dataUser") DataUser dataUser) {

BufferedReader br;
List<String> result2 = new ArrayList<String>();

try {
String line;
InputStream is = multipart.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
result2.add(line);
}
} catch (Exception e) {

}

for (int i = 0; i < result2.size(); i++) {
System.out.println("sentence" + result2.get(i));;
}

输出返回奇怪的符号。

然后我再次尝试:

InputStream inputStream;
try {
inputStream = multipart.getInputStream ();
BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (inputStream));
String line;
while ((line = bufferedReader.readLine()) != null)
{
System.out.println("linea era" + line);
}

} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

控制台输出显示奇怪的符号。

如何从上传的excel文件中读取数据?

最佳答案

据我了解,您需要读取 Excel 文件,获取数据,然后将其保存到数据库中。

Excel 文件以多种格式存储:

  • Excel 2003 二进制文件格式 (BIFF8)。
  • 基于 Xml 的格式(对于 .xlsx)

如果您只是尝试读取这样的文件,这将是一项艰巨的任务...

幸运的是,Apache POI有一个图书馆可以提供帮助。

可以下载here .

这是一个关于如何读取 excel 文件的简单示例:

try (InputStream inputStream = multipartFile.getInputStream())
{
Workbook wb = WorkbookFactory.create(inputStream);
// opening the first sheet
Sheet sheet = wb.getSheetAt(0);
// read the third row
Row row = sheet.getRow(2);
// read 4th cell
Cell cell = row.getCell(3);
// get the string value
String myValue = cell.getStringCellValue();

// store in the database...
} catch (IOException e) {
//TODO
}

关于java - 将上传的excel存入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51443063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com