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();
|
}
|
}
|