EasyExcel示例(阿里巴巴)基於Maven


首先感謝阿里巴巴提供了easyexcel工具類,github地址:https://github.com/alibaba/easyexcel

注意!!這里只是一個簡單的示例,VC大法即可使用,對於復雜的execl導出可能會出現問題。

另Execl文件后綴為xlsx。

  1、環境搭建

    jar包依賴

 <!-- excel導入導出插件 -->
 <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>easyexcel</artifactId>
     <version>1.1.2-beat1</version>
 </dependency>

    2、代碼

public class MyExcel {
    //
    @Test
    public void simpleRead() {
        FileInputStream fileInput;
        try {
            fileInput = new FileInputStream("F://javaio文件目錄//hss.xlsx");
            List<Object> read = EasyExcelFactory.read(fileInput, new Sheet(0,0));
            System.out.println(read);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        
    }
    //
    @Test
    public void simpleWrite() {
        FileOutputStream fileOut;
        try {
            File file = new File("F://javaio文件目錄//hss123.xlsx");
            if (file.exists()) {
                file.delete();
            }
            fileOut=new FileOutputStream("F://javaio文件目錄//hss123.xlsx");
            ExcelWriter writer = EasyExcelFactory.getWriter(fileOut);
            Sheet sheet = new Sheet(1,0);
            Sheet sheet2 = new Sheet(1,0);
            sheet.setSheetName("HelloWord");
            List<List<String>> data2 = new ArrayList<>();
            List<String> list2 = new ArrayList<>();
            List<String> list3 = new ArrayList<>();
            List<String> list4 = new ArrayList<>();
            List<String> list5 = new ArrayList<>();
            List<List<String>> data = new ArrayList<>();
            List<String> list1 = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                list1.add("123");
                list1.add("123");
                list1.add("123");
                list1.add("123");
                list1.add("123");
                data.add(list1);
            }
                list2.add("你好1");
                list3.add("你好2");
                list4.add("你好3");
                list5.add("你好4");
                data2.add(list2);
                data2.add(list3);
                data2.add(list4);
                data2.add(list5);
            sheet2.setHead(data2);
            writer.write0(null, sheet2);
            writer.write0(data, sheet);
            writer.finish();
            fileOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

     3.作為Util類使用(使用時調用

baseExportExcel

)具體class類型地址 https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/test/demo/write/DemoData.java

/**
 * excel工具類
 */
@Slf4j
public class EasyexcelUtil {

    protected static FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyyMMddHH:mm:ss");

    /**
     *
     * @param fileName 文件名
     * @param cameraReportStopList 普通vo類
     * @param entityModel 繼承BaseRowModel的模型class
     * @param response
     * @param <T>
     */
    public static <T extends BaseRowModel> void baseExportExcel(String fileName , List cameraReportStopList , Class<T> entityModel , HttpServletResponse response) {
        List<BaseRowModel> modelList = new ArrayList<>();
        if (StringUtils.isEmpty(cameraReportStopList)) {
            return;
        }
        cameraReportStopList.forEach(cameraReportStopVo -> {
            try{
                BaseRowModel cameraReportStopModel = entityModel.newInstance();
                BeanUtils.copyProperties(cameraReportStopVo , cameraReportStopModel);
                modelList.add(cameraReportStopModel);
            } catch (Exception e){
                log.info("excel export exception",e);
            }
        });

        try{
            writeExcel(response , modelList , fileName+fastDateFormat.format(new Date()) , "第一頁");
        } catch (Exception e){
            log.info("excel export exception",e);
            e.printStackTrace();
        }
    }

    /**
     * 導出 Excel :一個 sheet,帶表頭
     *
     * @param response HttpServletResponse
     * @param list 數據 list,每個元素為一個 BaseRowModel
     * @param fileName 導出的文件名
     * @param sheetName 導入文件的 sheet 名
     */
    public static void writeExcel(HttpServletResponse response,
                                  List<? extends BaseRowModel> list,
                                  String fileName,
                                  String sheetName) throws Exception {
        ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);
        Class clazz = null;
        if (list.size() > 0) {
            clazz = list.get(0).getClass();
        } else {
            clazz = BaseRowModel.class;
        }
        Sheet sheet = new Sheet(1, 0, clazz);
        sheet.setSheetName(sheetName);
        writer.write(list, sheet);
        writer.finish();
    }

    /**
     * 導出文件時為Writer生成OutputStream
     * @param fileName
     * @param response
     * @return
     * @throws Exception
     */
    private static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            log.info("excel export exception",e);
            ExceptionCast.cast("導出失敗!");
        }
        return null;
    }


}

 


免責聲明!

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



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