mitao
2024-06-06 3d2b51ea4520533de5e78f88dddf5b5c7dce4247
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.sinata.core.util;
 
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
 
/**
 * Excel导入工具类
 */
public class ExcelImportUtil {
 
    /**
     * 将excel文件内容转换成集合
     */
    public static List<Map<String, String>> getMapList(MultipartFile file, String[] titles) throws IOException {
        String fileName = file.getOriginalFilename();
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = isExcel2003 ? new HSSFWorkbook(is) : new XSSFWorkbook(is);
        List<Map<String, String>> list = new LinkedList<>();
        int sheetNumber = wb.getNumberOfSheets();
        for (int i = 0; i < sheetNumber; i++) {
            Sheet sheet = wb.getSheetAt(i);
            int rowNumber = sheet.getLastRowNum();
            for (int r = 1; r <= rowNumber; r++) {
                Row row = sheet.getRow(r);
                if (row != null) {
//                    Integer num = (int)row.getCell(0).getNumericCellValue();
//                    String str = getCellValue(row.getCell(1));
                    Map<String, String> map = new HashMap<>();
                    for (int t = 0; t < titles.length; t++) {
                        map.put(titles[t], getCellValue(row.getCell(t)));
                    }
                    list.add(map);
                }
            }
        }
        return list;
    }
 
    private static String getCellValue(Cell cell) {
        if (cell == null) return null;
        cell.setCellType(Cell.CELL_TYPE_STRING);
        return cell.getStringCellValue();
    }
}