欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot使用AOP+反射實(shí)現(xiàn)Excel數(shù)據(jù)的讀取

 更新時(shí)間:2022年01月26日 16:48:55   作者:淺殤憶流年  
本文主要介紹了springboot使用AOP+反射實(shí)現(xiàn)Excel數(shù)據(jù)的讀取,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

如果我們遇到把excel表格中的數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫,首先我們要做的是:將excel中的數(shù)據(jù)先讀取出來。
因此,今天就給大家分享一個(gè)讀取Excel表格數(shù)據(jù)的代碼示例:

為了演示方便,首先我們創(chuàng)建一個(gè)Spring Boot項(xiàng)目;具體創(chuàng)建過程這里不再詳細(xì)介紹;

示例代碼主要使用了Apache下的poi的jar包及API;因此,我們需要在pom.xml文件中導(dǎo)入以下依賴:

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

/**
 * @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數(shù)據(jù)
     *
     * @param sheetName
     * @param object
     * @return
     */
    public List readFromExcelData(String sheetName, Object object) {
        List result = new ArrayList();

        // 獲取該對(duì)象的class對(duì)象
        Class class_ = object.getClass();

        // 獲得該類的所有屬性
        Field[] fields = class_.getDeclaredFields();

        // 讀取excel數(shù)據(jù)  獲得指定的excel表
        HSSFSheet sheet = workbook.getSheet(sheetName);

        // 獲取表格的總行數(shù)
        int rowCount = sheet.getLastRowNum() + 1; // 需要加一
        if (rowCount < 1) {
            return result;
        }

        // 獲取表頭的列數(shù)
        int columnCount = sheet.getRow(0).getLastCellNum();

        // 讀取表頭信息,確定需要用的方法名---set方法
        // 用于存儲(chǔ)方法名
        String[] methodNames = new String[columnCount]; // 表頭列數(shù)即為需要的set方法個(gè)數(shù)

        // 用于存儲(chǔ)屬性類型
        String[] fieldTypes = new String[columnCount];

        // 獲得表頭行對(duì)象
        HSSFRow titleRow = sheet.getRow(0);

        // 遍歷表頭列
        for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {

            // 取出某一列的列名
            String colName = titleRow.getCell(columnIndex).toString();
/*
            // 將列名的首字母字母轉(zhuǎn)化為大寫
            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;

            // 遍歷屬性數(shù)組
            for (int i = 0; i < fields.length; i++) {

                // 獲取屬性上的注解name值
                String name = fields[i].getAnnotation(ExcelField.class).name();

                // 屬性與表頭相等
                if (Objects.nonNull(name) && colName.equals(name)) {
                    //  將屬性類型放到數(shù)組中
                    fieldTypes[columnIndex] = fields[i].getType().getName();
                }
            }
        }

        // 逐行讀取數(shù)據(jù) 從1開始 忽略表頭
        for (int rowIndex = 1; rowIndex < rowCount; rowIndex++) {
            // 獲得行對(duì)象
            HSSFRow row = sheet.getRow(rowIndex);
            if (row != null) {
                Object obj = null;
                // 實(shí)例化該泛型類的對(duì)象一個(gè)對(duì)象
                try {
                    obj = class_.newInstance();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }

                // 獲得本行中各單元格中的數(shù)據(jù)
                for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
                    String data = row.getCell(columnIndex).toString();
                    // 獲取要調(diào)用方法的方法名
                    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); // 執(zhí)行該方法
                    break;
                case "java.lang.Integer":
                    method = class_.getDeclaredMethod(methodName, Integer.class);
                    Integer value = Integer.valueOf(data);
                    method.invoke(obj, value); // 執(zhí)行該方法
                    break;
                case "java.lang.Boolean":
                    method = class_.getDeclaredMethod(methodName, Boolean.class);
                    Boolean booleanValue = Boolean.getBoolean(data);
                    method.invoke(obj, booleanValue); // 執(zhí)行該方法
                    break;
                case "java.lang.Double":
                    method = class_.getDeclaredMethod(methodName, Double.class);
                    double doubleValue = Double.parseDouble(data);
                    method.invoke(obj, doubleValue); // 執(zhí)行該方法
                    break;
                case "java.math.BigDecimal":
                    method = class_.getDeclaredMethod(methodName, BigDecimal.class);
                    BigDecimal bigDecimal = new BigDecimal(data);
                    method.invoke(obj, bigDecimal); // 執(zhí)行該方法
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
}

ExcelField.java

import java.lang.annotation.*;

/**
?* @author xxkfz
?*/
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE}) //注解放置的目標(biāo)位置,METHOD是可注解在方法級(jí)別上
@Retention(RetentionPolicy.RUNTIME) //注解在哪個(gè)階段執(zhí)行
@Documented
public @interface ExcelField {
? ? String name() default "";
}

實(shí)體類 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;
}

函數(shù)測(cè)試

?@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表格數(shù)據(jù)

測(cè)試結(jié)果:

ExcelFileField(id=X0001, code=X0001, type=X0001, version=X0001)
ExcelFileField(id=X0002, code=X0002, type=X0002, version=X0002)

Process finished with exit code 0

 到此這篇關(guān)于springboot使用AOP+反射實(shí)現(xiàn)Excel數(shù)據(jù)的讀取的文章就介紹到這了,更多相關(guān)springboot實(shí)現(xiàn)Excel讀取內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論