读取excel
pom.xml
<!-- poi操作 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
代码
main入口
public static void main(String[] args) {
String filePathName = "D://YDY//AABB.xlsx";
Workbook workbook = null;
FileInputStream in = null;
try {
try {
in = new FileInputStream(filePathName);
workbook = new HSSFWorkbook(in);
} catch (OfficeXmlFileException e) {
System.out.println("版本不兼容,HSSF切换XSSF");
if (in != null) {
in.close();
in = null;
System.out.println("关闭流");
}
in = new FileInputStream(filePathName);
workbook = new XSSFWorkbook(in);
System.out.println("重新创建流");
}
if (workbook == null) return;
Sheet sheetAt0 = workbook.getSheetAt(0);
// 取第一行,表头
Row headRow = sheetAt0.getRow(0);
Iterator<Cell> headIterator = headRow.iterator();
// 映射关系
Map<String, Integer> map = new TreeMap<>();
while (headIterator.hasNext()) {
Cell next = headIterator.next();
String stringCellValue = next.getStringCellValue();
int columnIndex = next.getColumnIndex();
map.put(stringCellValue, columnIndex);
}
int lastRowNum = sheetAt0.getLastRowNum();
// 第二行开始取数据
List<PlanModel> list = new ArrayList<>(lastRowNum);
for (int i = 1; i <= lastRowNum; i++) {
Row row = sheetAt0.getRow(i);
Class cls = PlanModel.class;
PlanModel planModel = (PlanModel) cls.newInstance();
list.add(planModel);
Field[] declaredFields = cls.getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
MyExcelAnnotation annotation = field.getAnnotation(MyExcelAnnotation.class);
if (annotation != null) {
String name = annotation.name();
Integer integer = map.get(name);
if (integer == null) continue;
Cell cell = row.getCell(integer);
// TODO 全部转字符类型了,应该具体类型具体判断
String stringCellValue = cell.getStringCellValue(); // cell.getNumericCellValue();
Method method = cls.getDeclaredMethod("set" + upperCaseFirstChar(field.getName()), String.class);
method.invoke(planModel, stringCellValue);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 首字符大写
*
* @param str
* @return
*/
private static String upperCaseFirstChar(String str) {
return Character.toUpperCase(str.charAt(0)) + str.substring(1);
}
注解类 MyExcelAnnotation
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyExcelAnnotation {
String name();
}
数据实体类对象Model
import lombok.Data;
@Data
public class PlanModel {
/**
* XX
*/
@MyExcelAnnotation(name = "XX")
private String XX;
// ...其他属性
}