首页 > 解决方案 > Spring Boot - 处理 CSV 以及 Excel 多部分文件

问题描述

我在 Spring Boot 应用程序中有一个 REST API,它接收一个 Multipart 文件类型的参数。

用户可能会导入需要处理的巨大尺寸的 CSV 文件或 Excel(.xlsx / .xsl) 文件。

我正在使用 Apache POI 读取 Excel 类型的文件,它工作正常。对于我现有的代码,我如何有效地处理 CSV 文件读取

下面是Excel文件读取代码:

    @RequestMapping(value="/read", method = RequestMethod.POST)
    @Transactional
    public Map<String, String> read(@RequestParam("file") MultipartFile file) {
    
    Map<String, String> response = new ArrayList();
    
    if (!file.isEmpty()) {
        ByteArrayInputStream stream;
        Workbook wb;
        StringBuilder contentSb = new StringBuilder();
        
        try {
            stream = new   ByteArrayInputStream(file.getBytes());
            wb = WorkbookFactory.create(stream);
            org.apache.poi.ss.usermodel.Sheet sheet = wb.getSheetAt(wb.getActiveSheetIndex());
            
            Iterator<Row> rowIterator = sheet.rowIterator();
            System.out.println("Processing Excel file");
            for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                  Row row = sheet.getRow(rowIndex);
                  if (row != null) {
                    Cell cell = row.getCell(0);
                    if (cell != null) {
                        contentSb.append(cell.getStringCellValue()+",");
                    }
                  }
                }
            System.out.println("Processed Excel file");
            return response;
            
        } catch (Exception e) {     
            e.printStackTrace();                
        } 
    }
    else {
        return response;
    }
}

先感谢您!

标签: spring-bootcsvapache-poiopencsv

解决方案


推荐阅读