導入導出筆記-easyExcel初探(表格導入和模板化導出)


前言

本文使用的EasyExcel Alibaba和EasyPoi Apache技術棧分析

  • EasyExcel Dependency

  • EasyPoi Dependency


1、需求一:表格化需求導入導出(難度星級:☆)

導入導出模板

實體對象

這里我們用到了一個注解com.alibaba.excel.annotation.ExcelProperty

@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ExcelProperty {

    /**
     * The name of the sheet header.
     *
     * <p>
     * write: It automatically merges when you have more than one head
     * <p>
     * read: When you have multiple heads, take the first one
     *
     * @return The name of the sheet header
     */
    String[] value() default {""};

    /**
     * Index of column
     *
     * Read or write it on the index of column,If it's equal to -1, it's sorted by Java class.
     *
     * priority: index &gt; order &gt; default sort
     *
     * @return Index of column
     */
    int index() default -1;

    /**
     * Defines the sort order for an column.
     *
     * priority: index &gt; order &gt; default sort
     *
     * @return Order of column
     */
    int order() default Integer.MAX_VALUE;

    /**
     * Force the current field to use this converter.
     *
     * @return Converter
     */
    Class<? extends Converter> converter() default AutoConverter.class;

    /**
     *
     * default @see com.alibaba.excel.util.TypeUtil if default is not meet you can set format
     *
     * @return Format string
     * @deprecated please use {@link com.alibaba.excel.annotation.format.DateTimeFormat}
     */
    @Deprecated
    String format() default "";
}

此處使用到的value注解,其余屬性不擴展,有想了解的東西可以關注公眾號“技術小邱”了解
注意,導出時此處value值要和excel值完全匹配,包括空格

  • 導入:解析excel
    EasyExcel.read(file.getInputStream()).head(Student.class).autoCloseStream(true) .autoTrim(true).sheet().doReadSync()
  • 導出:生成excel
WriteSheet studentSheet = EasyExcel.writerSheet("學生信息").head(ClaimReportListExportDTO.class).build();
excelWriter.write(studentList, studentSheet);

2、模板化導出(難度:☆☆☆)

模板樣式

首先我們需要更換模板,填充代入代碼

第一步:獲取模板輸入流信息(讀取模板信息)
InputStream in = this.getClass().getResourceAsStream(fileName)
第二步:轉換成輸出流(寫入目標文件)

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > -1) {
   outputStream.write(buffer, 0, len);
}
outputStream.flush();
in.close();

第三步:目標寫入

WriteSheet writeSheet = EasyExcel.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
excelWriter.fill(studentInfoList, fillConfig, writeSheet);
ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(byteArrayInputStream)
                    .autoCloseStream(Boolean.TRUE).build();
excelWriter.finish();

這樣就完成對應的導出了

以上均可以通過EasyExcel實現,EasyPoi目前運用比較多的是列表動態擴展,后面的博客將會講到
大家可以關注下公眾號,回復EasyExcel獲取更多資料


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM