这个表是某个xls文件的sheet2,要求用反射读取excel文件并转化为list,循环不要写死,可以使用poi包。只读取图中的学生数据,所以对行数和列数有要求,我想知道这个行和列应该怎么写
反射机制是java的一种思想,很多代码都有反射机制的应用,poi读取Excel不难吧
可以参考这个 https://blog.csdn.net/weixin_30650859/article/details/98693262
我是直接使用POI读取的包,POI内部应该使用的是反射吧
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632
public static class Student{
private String studentId;
private String studentName;
private String age;
private String startTime;
private String text;
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
public static List<Student> readStudent() throws IOException {
String path = "C:\\Users\\admin\\Desktop\\student.xlsx";
List<Student> studentList = new ArrayList<>();
String[] fields = new String[]{"studentId","studentName","age","startTime","text"};
File file = new File(path);
InputStream inputStream = new FileInputStream(file);
String fileName = file.getName();
Workbook workbook = fileName.endsWith("xlsx") ? new XSSFWorkbook(inputStream) : new HSSFWorkbook(inputStream);
//指定是第几张sheet 第一张是 0
Sheet hssfSheet = workbook.getSheetAt(0);
int last = hssfSheet.getLastRowNum();
int first = hssfSheet.getFirstRowNum();
//从上往下读取 控制起止行数
for (int rowIndex = first + 1; rowIndex <= last; rowIndex++) {
Row row = hssfSheet.getRow(rowIndex);
//控制读取的列数开始
int firstCellNum = row.getFirstCellNum();//获取所在行的第一个行号
Map<String,Object> map = new HashMap<>();
for (int columnIndex = firstCellNum; columnIndex < fields.length; columnIndex++) {
Cell cell = row.getCell(columnIndex);
if(cell == null){
map.put(fields[columnIndex],"");
}else {
cell.setCellType(Cell.CELL_TYPE_STRING);
String value = row.getCell(columnIndex).getStringCellValue();
if(value.contains("'")){
value = value.replace("'","''");
}
map.put(fields[columnIndex], value);
}
}
Student student = JSON.parseObject(JSON.toJSONString(map),Student.class);
studentList.add(student);
}
return studentList;
}
结果:
使用:
com.alibaba.fastjson
org.apache.poi