溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2022-01-27 09:11:04 來源:億速云 閱讀:187 作者:kk 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)springboot如何使用AOP+反射實現(xiàn)Excel數(shù)據(jù)的讀取,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

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

為了演示方便,首先我們創(chuàng)建一個Spring Boot項目;具體創(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();

        // 獲取該對象的class對象
        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方法
        // 用于存儲方法名
        String[] methodNames = new String[columnCount]; // 表頭列數(shù)即為需要的set方法個數(shù)

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

        // 獲得表頭行對象
        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++) {
            // 獲得行對象
            HSSFRow row = sheet.getRow(rowIndex);
            if (row != null) {
                Object obj = null;
                // 實例化該泛型類的對象一個對象
                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是可注解在方法級別上
@Retention(RetentionPolicy.RUNTIME) //注解在哪個階段執(zhí)行
@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;
}

函數(shù)測試

 @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ù)

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

測試結(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

springboot是什么

springboot一種全新的編程規(guī)范,其設(shè)計目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程,SpringBoot也是一個服務(wù)于框架的框架,服務(wù)范圍是簡化配置文件。

關(guān)于springboot如何使用AOP+反射實現(xiàn)Excel數(shù)據(jù)的讀取就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI