如果我们遇到把excel表格中的数据导入到数据库,首先我们要做的是:将excel中的数据先读取出来。 因此,今天就给大家分享一个读取Excel表格数据的代码示例:
为了演示方便,首先我们创建一个Spring Boot项目;具体创建过程这里不再详细介绍;
示例代码主要使用了Apache下的poi的jar包及API;因此,我们需要在pom.xml 文件中导入以下依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.13</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.13</version>
</dependency>
主要代码:
ExcelUtils.java
import com.example.springbatch.xxkfz.annotation.ExcelField;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Slf4j
public class ExcelUtils {
private HSSFWorkbook workbook;
public ExcelUtils(String fileDir) {
File file = new File(fileDir);
try {
workbook = new HSSFWorkbook(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public List readFromExcelData(String sheetName, Object object) {
List result = new ArrayList();
Class class_ = object.getClass();
Field[] fields = class_.getDeclaredFields();
HSSFSheet sheet = workbook.getSheet(sheetName);
int rowCount = sheet.getLastRowNum() + 1;
if (rowCount < 1) {
return result;
}
int columnCount = sheet.getRow(0).getLastCellNum();
String[] methodNames = new String[columnCount];
String[] fieldTypes = new String[columnCount];
HSSFRow titleRow = sheet.getRow(0);
for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
String colName = titleRow.getCell(columnIndex).toString();
String fieldName = fields[columnIndex].getName();
String UpperFieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1, fieldName.length());
methodNames[columnIndex] = "set" + UpperFieldName;
for (int i = 0; i < fields.length; i++) {
String name = fields[i].getAnnotation(ExcelField.class).name();
if (Objects.nonNull(name) && colName.equals(name)) {
fieldTypes[columnIndex] = fields[i].getType().getName();
}
}
}
for (int rowIndex = 1; rowIndex < rowCount; rowIndex++) {
HSSFRow row = sheet.getRow(rowIndex);
if (row != null) {
Object obj = null;
try {
obj = class_.newInstance();
} catch (Exception e1) {
e1.printStackTrace();
}
for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
String data = row.getCell(columnIndex).toString();
String methodName = methodNames[columnIndex];
obj = this.valueConvert(fieldTypes[columnIndex], methodName, class_, obj, data);
}
result.add(obj);
}
}
return result;
}
private Object valueConvert(String fieldType, String methodName, Class class_, Object obj, String data) {
Method method = null;
if (Objects.isNull(fieldType) || Objects.isNull(methodName) || Objects.isNull(class_) || Objects.isNull(obj)) {
return obj;
}
try {
switch (fieldType) {
case "java.lang.String":
method = class_.getDeclaredMethod(methodName, String.class);
method.invoke(obj, data);
break;
case "java.lang.Integer":
method = class_.getDeclaredMethod(methodName, Integer.class);
Integer value = Integer.valueOf(data);
method.invoke(obj, value);
break;
case "java.lang.Boolean":
method = class_.getDeclaredMethod(methodName, Boolean.class);
Boolean booleanValue = Boolean.getBoolean(data);
method.invoke(obj, booleanValue);
break;
case "java.lang.Double":
method = class_.getDeclaredMethod(methodName, Double.class);
double doubleValue = Double.parseDouble(data);
method.invoke(obj, doubleValue);
break;
case "java.math.BigDecimal":
method = class_.getDeclaredMethod(methodName, BigDecimal.class);
BigDecimal bigDecimal = new BigDecimal(data);
method.invoke(obj, bigDecimal);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}
ExcelField.java
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelField {
String name() default "";
}
实体类 ExcelFileField.java
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class ExcelFileField {
@ExcelField(name = "id")
private String id;
@ExcelField(name = "code")
private String code;
@ExcelField(name = "type")
private String type;
@ExcelField(name = "version")
private String version;
}
函数测试
@Test
void readExcel() {
ExcelUtils utils = new ExcelUtils("E:/test.xls");
ExcelFileField interfaceField = new ExcelFileField();
List list = utils.readFromExcelData("sheet1", interfaceField);
for (int i = 0; i < list.size(); i++) {
ExcelFileField item = (ExcelFileField) list.get(i);
System.out.println(item.toString());
}
}
Excel表格数据
测试结果:
ExcelFileField(id=X0001, code=X0001, type=X0001, version=X0001)
ExcelFileField(id=X0002, code=X0002, type=X0002, version=X0002)
Process finished with exit code 0
本篇文章到这里就基本结束了,如果这篇文章对你有帮助,希望大家能留下你的点赞、 关注、 分享、 留言??????
|