wisdomisite-java/src/main/java/com/zhgd/xmgl/util/ReadExcelUtils.java
2024-04-14 21:05:01 +08:00

86 lines
3.1 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.zhgd.xmgl.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @program: wisdomSite
* @description:
* @author: Mr.Peng
* @create: 2022-06-06 16:11
**/
@Slf4j
public class ReadExcelUtils {
public static List<Map<String, String>> jxlExlToList(InputStream is, int index) throws Exception {
HSSFWorkbook book = null;
List<Map<String, String>> list = null;
String companyId = null;
//Map<String,Object> map=new HashMap<>();
try {
book = new HSSFWorkbook(is);// 创建一个新的写入工作簿
Sheet sheet = book.getSheetAt(0);
//int totalRows = sheet.getLastRowNum();
int totalRows = sheet.getPhysicalNumberOfRows();
//int totalColumns = sheet.getColumns();
Row xssfRow = sheet.getRow(index);
int totalColumns = xssfRow.getLastCellNum();
if (totalColumns <= 0) {
return null;
}
//读取指定行作为Map中的key
List<String> tableHeaderlist = new ArrayList<>();
for (int i = 0; i < totalColumns; i++) {
String value = ExcelUtils.getCellValue(sheet, xssfRow.getCell(i));
if (tableHeaderlist.contains(value)) {
value = value + "(1)";
}
if (StringUtils.isNotEmpty(value)) {
value = value.replaceAll("[\\t\\n\\r]", "");
}
tableHeaderlist.add(value);
}
//将指定行后面每一行存为Map集合然后存为list
list = new ArrayList<>();
Map<String, String> rowData = new LinkedHashMap<>();
int start = 1 + index;
for (int i = start; i < totalRows; i++) {
xssfRow = sheet.getRow(i);
rowData = new LinkedHashMap<>(totalColumns);
for (int j = 0; j < xssfRow.getLastCellNum(); j++) {
if (j < totalColumns) {
if (StringUtils.isNotEmpty(tableHeaderlist.get(j).toString())) {
if (xssfRow.getCell(j) != null) {
String value = ExcelUtils.getCellValue(sheet, xssfRow.getCell(j));
rowData.put(tableHeaderlist.get(j).toString(), value);
} else {
rowData.put(tableHeaderlist.get(j).toString(), "");
}
}
}
}
if (rowData.size() > 0) {
list.add(rowData);
}
}
log.info("工作簿读取数据成功!");
} catch (Exception e) {
log.error("error", e);
}
return list;
}
}