将上传的Excel保存到数据库中

时间:2018-07-20 12:57:19

标签: java excel spring-mvc spring-boot

我有一个代码,我的客户端将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文件中读取数据?

1 个答案:

答案 0 :(得分:3)

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

Excel文件以各种格式存储:

  • Excel 2003 Binary文件格式(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
    }