1.引入依赖
XML
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version>
</dependency>
<!--<!– Poi-tl Word 模板引擎–>-->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.12.2</version>
</dependency>
示例代码
java
public List<Item> importItem(InputStream inputStream) throws IOException {
Workbook wb = new XSSFWorkbook(inputStream);
String[] titles = new String[]{"学号","姓名","性别"};
try {
Sheet sheet = wb.getSheet(0);
Row titleRow = sheet.getRow(1);
Map<String,String> rowData = getRowData(titleRow,titles);
for(String k:rowData.keySet()){
String v = rowData.get(k);
if(!k.equals(v)){
throw new RuntimeException(String.format("错误的列标题:%s,导入失败!",v));
}
}
List<Item> items = new LinkedList<>();
int rows = sheet.getPhysicalNumberOfRows();
for(int j = 2; j < rows; j++){
Row row = sheet.getRow(j);
Map<String,String> data = getRowData(row,titles);
if(data.size()>0){
Item item = new Item();
try{
item.setStudentId(data.get(titles[0]).trim());
item.setName(data.get(titles[1]).trim());
item.setSex(data.get(titles[2]).trim());
}catch(Exception e){
throw new RuntimeException(String.format("第%s,导入失败,请检查数据!",j+1));
}
items.add(item);
}
}
return new HashMap<>(){{
put("items", items);
}};
}catch(Exception e){
throw new RuntimeException(e.getMessage());
}
}
public static Map<String,String> getRowData(Row row,String[] titles){
if(null == row || isRowEmpty(row)){
return new HashMap<>();
}
int cells = titles.length;
Map<String,String> data = new LinkedHashMap<>();
for(int i = 0; i < cells; i++){
Cell cell = row.getCell(i);
if(cell == null || isEmpty(cell.toString())){
data.put(titles[i],"");
}else{
switch(cell.getCellType()){
case NUMERIC:
DecimalFormat df = new DecimalFormat("0.############");
String s = df.format(cell.getNumericCellValue());
data.put(titles[i],s);
break;
case STRING:
data.put(titles[i],cell.getStringCellValue());
break;
case BLANK:
data.put(titles[i],"");
break;
case BOOLEAN:
data.put(titles[i],Boolean.valueOf(cell.getBooleanCellValue()).toString());
break;
case FORMULA:
data.put(titles[i],cell.getRichStringCellValue().toString());
break;
default:
data.put(titles[i],cell.toString());
break;
}
}
}
return data;
}
public static boolean isRowEmpty(Row row) {
if(null == row){
return true;
}
for(int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++){
Cell cell = row.getCell(i);
if(cell != null && cell.getCellType != CellType.BLANK)
return false;
}
return true;
}
public static boolean isEmpty(String str){
if(Objects.isNull(str)){
return true;
}else{
return str.trim().length() == 0;
}
}