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

问题描述 投票:9回答:1

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

java excel spring-mvc spring-boot
1个回答
3
投票

据我所知,您需要读取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
    }
© www.soinside.com 2019 - 2024. All rights reserved.