springboot Excel处理

导入依赖

        <!--excel 处理-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>

核心代码


@RestController
public class Upload {

    @RequestMapping("file/upload")
    public List<Object> pubggupload(@RequestParam("file") MultipartFile file) throws Exception {
        String name = file.getOriginalFilename();
        List<Object> list = ExcelUtils.excelToShopIdList(file.getInputStream());
        return list;

    }
}



import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ExcelUtils {

    public static List<Object> excelToShopIdList(InputStream inputStream) {

        List<Object> list = new ArrayList<>();
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(inputStream);
            inputStream.close();
            //工作表对象
            Sheet sheet = workbook.getSheetAt(0);
            //总行数
            int rowLength = sheet.getLastRowNum() + 1;
            System.out.println("总行数有多少行" + rowLength);

            //总列数
            int colLength = sheet.getRow(0).getLastCellNum();
            System.out.println("总列数有多少列" + colLength);
            //得到指定的单元格
            for (int i = 0; i < rowLength; i++) {
                Row row = sheet.getRow(i);
                for (int j = 1; j < colLength + 1; j++) {
                    Cell cell = row.getCell(j);
                    log.info(cell.toString());
                    list.add(cell);
                }
            }

        } catch (
                Exception e) {
            log.error("parse excel file error :", e);
        }
        return list;
    }

}

调用方式

注意把Content-type设置为multipart/form-data

git

https://github.com/lexiaoyao1995/excelDemo

posted @ 2020-10-21 12:01  刃牙  阅读(443)  评论(0编辑  收藏  举报