【问题标题】:Save uploaded excel in database将上传的excel保存在数据库中
【发布时间】:2018-07-20 12:57:18
【问题描述】:

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

【问题讨论】:

  • 您有什么问题吗?请在需要帮助的地方更具体地描述您的问题。
  • 我需要读取 MultipartFile ... 因为我需要在数据库中插入 Excell (MultipartFile) 的数据,但是当我使用 getInputStream o 和 ByteArray 读取 MultipartFile 时,我总是得到罕见的符号

标签: java excel spring-mvc spring-boot


【解决方案1】:

据我了解,您需要读取 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
    }

【讨论】:

    猜你喜欢
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多