java
主页 > 软件编程 > java >

springboot使用AOP+反射实现Excel数据的读取

2022-01-26 | 秩名 | 点击:

如果我们遇到把excel表格中的数据导入到数据库,首先我们要做的是:将excel中的数据先读取出来。
因此,今天就给大家分享一个读取Excel表格数据的代码示例:

为了演示方便,首先我们创建一个Spring Boot项目;具体创建过程这里不再详细介绍;

示例代码主要使用了Apache下的poi的jar包及API;因此,我们需要在pom.xml文件中导入以下依赖:

1

2

3

4

5

6

7

8

9

10

        <dependency>

            <groupId>org.apache.poigroupId>

            <artifactId>poiartifactId>

            <version>3.13version>

        dependency>

        <dependency>

            <groupId>org.apache.poigroupId>

            <artifactId>poi-ooxmlartifactId>

            <version>3.13version>

        dependency>

主要代码:

ExcelUtils.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

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;

 

/**

 * @author xxkfz

 * Excel工具类

 */

 

@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();

        }

    }

 

    /**

     * 读取Excel数据

     *

     * @param sheetName

     * @param object

     * @return

     */

    public List readFromExcelData(String sheetName, Object object) {

        List result = new ArrayList();

 

        // 获取该对象的class对象

        Class class_ = object.getClass();

 

        // 获得该类的所有属性

        Field[] fields = class_.getDeclaredFields();

 

        // 读取excel数据  获得指定的excel表

        HSSFSheet sheet = workbook.getSheet(sheetName);

 

        // 获取表格的总行数

        int rowCount = sheet.getLastRowNum() + 1; // 需要加一

        if (rowCount < 1) {

            return result;

        }

 

        // 获取表头的列数

        int columnCount = sheet.getRow(0).getLastCellNum();

 

        // 读取表头信息,确定需要用的方法名---set方法

        // 用于存储方法名

        String[] methodNames = new String[columnCount]; // 表头列数即为需要的set方法个数

 

        // 用于存储属性类型

        String[] fieldTypes = new String[columnCount];

 

        // 获得表头行对象

        HSSFRow titleRow = sheet.getRow(0);

 

        // 遍历表头列

        for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {

 

            // 取出某一列的列名

            String colName = titleRow.getCell(columnIndex).toString();

/*

            // 将列名的首字母字母转化为大写

            String UColName = Character.toUpperCase(colName.charAt(0)) + colName.substring(1, colName.length());

 

            // set方法名存到methodNames

            methodNames[columnIndex] = "set" + UColName;

*/

            //

            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++) {

 

                // 获取属性上的注解name值

                String name = fields[i].getAnnotation(ExcelField.class).name();

 

                // 属性与表头相等

                if (Objects.nonNull(name) && colName.equals(name)) {

                    //  将属性类型放到数组中

                    fieldTypes[columnIndex] = fields[i].getType().getName();

                }

            }

        }

 

        // 逐行读取数据 从1开始 忽略表头

        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;

    }

 

    /**

     * @param fieldType  字段类型

     * @param methodName 方法名

     * @param class_

     * @param data

     * @return

     */

    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

1

2

3

4

5

6

7

8

9

10

11

import java.lang.annotation.*;

 

/**

 * @author xxkfz

 */

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE}) //注解放置的目标位置,METHOD是可注解在方法级别上

@Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行

@Documented

public @interface ExcelField {

    String name() default "";

}

实体类 ExcelFileField.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

@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;

}

函数测试

1

2

3

4

5

6

7

8

9

10

 @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

原文链接:https://blog.csdn.net/weixin_43759352/article/details/122656506
相关文章
最新更新