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

Java使用poi做加自定義注解實(shí)現(xiàn)對(duì)象與Excel相互轉(zhuǎn)換

 更新時(shí)間:2021年05月28日 16:31:51   作者:Acmen-zym  
這篇文章主要介紹了Java使用poi做加自定義注解實(shí)現(xiàn)對(duì)象與Excel相互轉(zhuǎn)換,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

引入依賴

maven

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

Gradle

implementation group: 'org.apache.poi', name: 'poi', version: '3.17'

代碼展示

1、自定義注解類

@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = ElementType.FIELD)
public @interface Excel {
    String name();//列的名字

    int width() default 6000;//列的寬度

    int index() default -1;//決定生成的順序

    boolean isMust() default true; // 是否為必須值,默認(rèn)是必須的
}

2、Java的Excel對(duì)象,只展現(xiàn)了field,get與set方法就忽略了

public class GoodsExcelModel {
    @Excel(name = "ID_禁止改動(dòng)", index = 0, width = 0)
    private Long picId;//picId
    @Excel(name = "產(chǎn)品ID_禁止改動(dòng)", index = 1, width = 0)
    private Long productId;
    @Excel(name = "型號(hào)", index = 3)
    private String productName;//產(chǎn)品型號(hào)
    @Excel(name = "系列", index = 2)
    private String seriesName;//系列名字
    @Excel(name = "庫存", index = 5)
    private Long quantity;
    @Excel(name = "屬性值", index = 4)
    private String propValue;
    @Excel(name = "價(jià)格", index = 6)
    private Double price;
    @Excel(name = "商品編碼", index = 7, isMust = false)
    private String outerId;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long dbId; // 數(shù)據(jù)庫自增長id

    private Date createTime; // 記錄創(chuàng)建時(shí)間
 }

3、Excel表格與對(duì)象轉(zhuǎn)換的工具類,使用時(shí)指定泛型參數(shù)和泛型的class即可

public class ExcelUtil {
    private static final String GET = "get";
    private static final String SET = "set";
    private static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);

    /**
     * 將對(duì)象轉(zhuǎn)換成Excel
     *
     * @param objList 需要轉(zhuǎn)換的對(duì)象
     * @return 返回是poi中的對(duì)象
     */
    public static HSSFWorkbook toExcel(List objList) {
        if (CollectionUtils.isEmpty(objList)) throw new NullPointerException("無效的數(shù)據(jù)");
        Class aClass = objList.get(0).getClass();
        Field[] fields = aClass.getDeclaredFields();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        for (int i = 0; i < objList.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);//要從第二行開始寫
            HSSFRow topRow = null;
            if (i == 0) topRow = sheet.createRow(0);
            for (Field field : fields) {
                Excel excel = field.getAnnotation(Excel.class);//得到字段是否使用了Excel注解
                if (excel == null) continue;
                HSSFCell cell = row.createCell(excel.index());//設(shè)置當(dāng)前值放到第幾列
                String startName = field.getName().substring(0, 1);
                String endName = field.getName().substring(1, field.getName().length());
                String methodName = new StringBuffer(GET).append(startName.toUpperCase()).append(endName).toString();
                try {
                    Method method = aClass.getMethod(methodName);//根據(jù)方法名獲取方法,用于調(diào)用
                    Object invoke = method.invoke(objList.get(i));
                    if (invoke == null) continue;
                    cell.setCellValue(invoke.toString());
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                if (topRow == null) continue;
                HSSFCell topRowCell = topRow.createCell(excel.index());
                topRowCell.setCellValue(excel.name());
                sheet.setColumnWidth(excel.index(), excel.width());
            }
        }

        return workbook;
    }

    /**
     * 將Excel文件轉(zhuǎn)換為指定對(duì)象
     *
     * @param file 傳入的Excel
     * @param c    需要被指定的class
     * @return
     * @throws IOException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static <T> List<T> excelFileToObject(MultipartFile file, Class<T> c) throws IOException, IllegalAccessException, InstantiationException {
        //key為反射得到的下標(biāo),value為對(duì)于的set方法
        Map<Integer, String> methodMap = new HashMap<>();
        //保存第一列的值與對(duì)應(yīng)的下標(biāo),用于驗(yàn)證用戶是否刪除了該列,key為下標(biāo),value為名字
        Map<Integer, String> startRowNameMap = new HashMap<>();
        //用來記錄當(dāng)前參數(shù)是否為必須的
        Map<Integer, Boolean> fieldIsMustMap = new HashMap<>();
        //得到所有的字段
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            Excel excel = field.getAnnotation(Excel.class);
            if (excel == null) continue;
            String startName = field.getName().substring(0, 1);
            String endName = field.getName().substring(1, field.getName().length());
            String methodName = new StringBuffer(SET).append(startName.toUpperCase()).append(endName).toString();
            methodMap.put(excel.index(), methodName);
            startRowNameMap.put(excel.index(), excel.name());
            fieldIsMustMap.put(excel.index(), excel.isMust());
        }

        String fileName = file.getOriginalFilename();
        Workbook wb = fileName.endsWith(".xlsx") ? new XSSFWorkbook(file.getInputStream()) : new HSSFWorkbook(file.getInputStream());
        Sheet sheet = wb.getSheetAt(0);
        Row sheetRow = sheet.getRow(0);
        for (Cell cell : sheetRow) {
            Integer columnIndex = cell.getColumnIndex();
            if (cell.getCellTypeEnum() != CellType.STRING) throw new ExcelException("excel校驗(yàn)失敗, 請勿刪除文件中第一行數(shù)據(jù) !!!");
            String value = cell.getStringCellValue();
            String name = startRowNameMap.get(columnIndex);
            if (name == null) throw new ExcelException("excel校驗(yàn)失敗,請勿移動(dòng)文件中任何列的順序!!!");
            if (!name.equals(value)) throw new ExcelException("excel校驗(yàn)失敗,【" + name + "】列被刪除,請勿刪除文件中任何列 !!!");
        }
        sheet.removeRow(sheetRow);//第一行是不需要被反射賦值的
        List<T> models = new ArrayList<>();
        for (Row row : sheet) {
            if (row == null || !checkRow(row)) continue;
            T obj = c.newInstance();//創(chuàng)建新的實(shí)例化對(duì)象
            Class excelModelClass = obj.getClass();
            startRowNameMap.entrySet().forEach(x -> {
                Integer index = x.getKey();
                Cell cell = row.getCell(index);
                String methodName = methodMap.get(index);
                if (StringUtils.isEmpty(methodName)) return;
                List<Method> methods = Lists.newArrayList(excelModelClass.getMethods()).stream()
                        .filter(m -> m.getName().startsWith(SET)).collect(Collectors.toList());
                String rowName = startRowNameMap.get(index);//列的名字
                for (Method method : methods) {
                    if (!method.getName().startsWith(methodName)) continue;
                    //檢測value屬性
                    String value = valueCheck(cell, rowName, fieldIsMustMap.get(index));
                    //開始進(jìn)行調(diào)用方法反射賦值
                    methodInvokeHandler(obj, method, value);
                }
            });
            models.add(obj);
        }
        return models;
    }

    /**
     * 檢測當(dāng)前需要賦值的value
     *
     * @param cell    當(dāng)前循環(huán)行中的列對(duì)象
     * @param rowName 列的名字{@link Excel}中的name
     * @param isMust  是否為必須的
     * @return 值
     */
    private static String valueCheck(Cell cell, String rowName, Boolean isMust) {
        //有時(shí)候刪除單個(gè)數(shù)據(jù)會(huì)造成cell為空,也可能是value為空
        if (cell == null && isMust) {
            throw new ExcelException("excel校驗(yàn)失敗,【" + rowName + "】中的數(shù)據(jù)禁止單個(gè)刪除");
        }
        if (cell == null) return null;
        cell.setCellType(CellType.STRING);
        String value = cell.getStringCellValue();
        if ((value == null || value.trim().isEmpty()) && isMust) {
            throw new ExcelException("excel校驗(yàn)失敗,【" + rowName + "】中的數(shù)據(jù)禁止單個(gè)刪除");
        }
        return value;
    }

    /**
     * 反射賦值的處理的方法
     *
     * @param obj      循環(huán)創(chuàng)建的需要賦值的對(duì)象
     * @param method 當(dāng)前對(duì)象期中一個(gè)set方法
     * @param value  要被賦值的內(nèi)容
     */
    private static void methodInvokeHandler(Object obj, Method method, String value) {
        Class<?> parameterType = method.getParameterTypes()[0];
        try {
            if (parameterType == null) {
                method.invoke(obj);
                return;
            }
            String name = parameterType.getName();
            if (name.equals(String.class.getName())) {
                method.invoke(obj, value);
                return;
            }
            if (name.equals(Long.class.getName())) {
                method.invoke(obj, Long.valueOf(value));
                return;
            }
            if (name.equals(Double.class.getName())) {
                method.invoke(obj, Double.valueOf(value));
            }

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    private static boolean checkRow(Row row) {
        try {
            if (row == null) return false;
            short firstCellNum = row.getFirstCellNum();
            short lastCellNum = row.getLastCellNum();
            if (firstCellNum < 0 && lastCellNum < 0) return false;
            if (firstCellNum != 0) {
                for (short i = firstCellNum; i < lastCellNum; i++) {
                    Cell cell = row.getCell(i);
                    String cellValue = cell.getStringCellValue();
                    if (!StringUtils.isBlank(cellValue)) return true;
                }
                return false;
            }
            return true;
        } catch (Exception e) {
            return true;
        }

    }

4、導(dǎo)出Excel與導(dǎo)入Excel的示例代碼

在這里插入圖片描述

在這里插入圖片描述

使用展示

1、選擇數(shù)據(jù)

在這里插入圖片描述

2、設(shè)置基本數(shù)據(jù),然后導(dǎo)出表格

在這里插入圖片描述

3、導(dǎo)出表格效果,在圖片中看到A和B列沒有顯示出來,這是因?yàn)槲覍⑵鋵挾扰渲脼榱?

在這里插入圖片描述

4、將必須參數(shù)刪除后上傳測試,如下圖中,商品編碼我設(shè)置isMust為false所以刪除數(shù)據(jù)就不會(huì)出現(xiàn)此問題。會(huì)提示驗(yàn)證失敗,具體錯(cuò)誤查看圖片

在這里插入圖片描述

在這里插入圖片描述

5、將列中值的順序調(diào)整測試,也會(huì)提示驗(yàn)證失敗,具體效果如下圖

在這里插入圖片描述

在這里插入圖片描述

6、正常上傳測試,具體效果下如圖

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

到此這篇關(guān)于Java使用poi做加自定義注解實(shí)現(xiàn)對(duì)象與Excel相互轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)Java 對(duì)象與Excel相互轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java中反射動(dòng)態(tài)代理接口的詳解及實(shí)例

    Java中反射動(dòng)態(tài)代理接口的詳解及實(shí)例

    這篇文章主要介紹了Java中反射動(dòng)態(tài)代理接口的詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下
    2017-04-04
  • SpringBoot獲取當(dāng)前運(yùn)行環(huán)境三種方式小結(jié)

    SpringBoot獲取當(dāng)前運(yùn)行環(huán)境三種方式小結(jié)

    在使用SpringBoot過程中,我們只需要引入相關(guān)依賴,然后在main方法中調(diào)用SpringBootApplication.run(應(yīng)用程序啟動(dòng)類.class)方法即可,那么SpringBoot是如何獲取當(dāng)前運(yùn)行環(huán)境呢,接下來由小編給大家介紹一下SpringBoot獲取當(dāng)前運(yùn)行環(huán)境三種方式,需要的朋友可以參考下
    2024-01-01
  • spring cloud 之 Feign 使用HTTP請求遠(yuǎn)程服務(wù)的實(shí)現(xiàn)方法

    spring cloud 之 Feign 使用HTTP請求遠(yuǎn)程服務(wù)的實(shí)現(xiàn)方法

    下面小編就為大家?guī)硪黄猻pring cloud 之 Feign 使用HTTP請求遠(yuǎn)程服務(wù)的實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-06-06
  • Java實(shí)現(xiàn)猜字小游戲

    Java實(shí)現(xiàn)猜字小游戲

    這篇文章給大家分享小編隨手寫的猜字小游戲,基于java代碼寫的,感興趣的朋友跟隨小編一起看看吧
    2019-11-11
  • RabbitMQ 最常用的三大模式實(shí)例解析

    RabbitMQ 最常用的三大模式實(shí)例解析

    這篇文章主要介紹了RabbitMQ 最常用的三大模式實(shí)例解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • Spring框架 注解配置事務(wù)控制的流程

    Spring框架 注解配置事務(wù)控制的流程

    這篇文章主要介紹了Spring框架 注解配置事務(wù)控制的流程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Java在ElasticSearch中使用LocalDatetime類型

    Java在ElasticSearch中使用LocalDatetime類型

    最近在開發(fā)一個(gè)搜索功能的需求的時(shí)候,遇到了LocalDatetime類型不能保存到ElasticSearch中的問題,這篇文章主要介紹了Java在ElasticSearch中使用LocalDatetime類型
    2023-10-10
  • JavaWeb開發(fā)中alias攔截器的使用方法

    JavaWeb開發(fā)中alias攔截器的使用方法

    本文給大家介紹在JavaWeb開發(fā)中alias攔截器的使用方法相關(guān)知識(shí),本文介紹的非常詳細(xì),具有參考借鑒價(jià)值,感興趣的朋友一起看下吧
    2016-08-08
  • Java中并行執(zhí)行任務(wù)的多種方式

    Java中并行執(zhí)行任務(wù)的多種方式

    在Java編程中,經(jīng)常會(huì)遇到需要并行執(zhí)行任務(wù)的情況,特別是在處理大量數(shù)據(jù)或者需要異步處理的場景下,本文將介紹幾種常用的并行執(zhí)行任務(wù)的方式,文中有詳細(xì)的代碼示例供大家參考,需要的朋友可以參考下
    2024-04-04
  • IDEA配置Maven的超詳細(xì)步驟

    IDEA配置Maven的超詳細(xì)步驟

    Maven是一個(gè)能使我們的java程序開發(fā)節(jié)省時(shí)間和精力,是開發(fā)變得相對(duì)簡單,還能使開發(fā)規(guī)范化的工具,下面這篇文章主要給大家介紹了關(guān)于IDEA配置Maven的超詳細(xì)步驟,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2022-08-08

最新評(píng)論