例子代碼:
第一步:
<!--Excel包--> <!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel --> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>1.1.2-beta5</version> </dependency>
第二步:
@Test public void ExportTest() throws IOException { //指定文件輸出位置 OutputStream outputStream =new FileOutputStream("H:/excel/file/myexcel3.xlsx"); ExcelWriter excelWriter =EasyExcelFactory.getWriter(outputStream); //將要輸出的內容填充到Sheet里 Sheet sheet =new Sheet(1,0,ExcelModel.class ); //設置sheet表名 sheet.setSheetName("my_three_excel"); /** * 寫數據到Write上下文中 * 第一個參數:要寫入的內容 * 第二個參數:要寫入的sheet目標 */ excelWriter.write(createModelList2(),sheet); excelWriter.finish(); outputStream.close(); }
第三步:
@Data public class ExcelMode extends BaseRowModel { @ExcelProperty(value = "姓名" ,index = 0) private String userName; @ExcelProperty(value = "年齡" ,index = 1) private String age; @ExcelProperty(value = "住址" ,index = 2) private String address; } private List<ExcelMode> createModelList (){ List<ExcelMode> list = new ArrayList<>(); for(int i=0; i<20;i++){ ExcelMode excelMode = new ExcelMode(); excelMode.setUserName("噠噠"+i); excelMode.setAge("22"); excelMode.setAddress("廣西"); list.add(excelMode); } return list; }
第四步:
@Data public class ExcelModel2 extends BaseRowModel { @ExcelProperty(value = {"name","name"},index = 0) private String name; @ExcelProperty(value ={"age","age"},index = 1) private String age; @ExcelProperty(value={"cash_value","高"},index = 2) private String cashvalue_high ; @ExcelProperty(value={"cash_value","中"},index = 3) private String cashvalue_during ; @ExcelProperty(value={"cash_value","低"},index = 4) private String cashvalue_low ; }