easyexcel(一)写

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>1.1.2-beat1</version>
        </dependency>

代码

public class WriteExcel {

    //无映射,有表头
    @Test
    public void noModel() throws FileNotFoundException {
        OutputStream out=new FileOutputStream("test2.xls");
        ExcelWriter writer=new ExcelWriter(out, ExcelTypeEnum.XLS);
        //创建sheet页
        Sheet sheet=new Sheet(1,0);
        sheet.setSheetName("sheet1");
        //写入的表数据
        List<List<String>> data=new ArrayList<>();
        for(int i=0;i<5;i++){
            List<String> item=new ArrayList<>();
            item.add("tom"+i);
            item.add(String.valueOf(10+i));
            item.add("cn");
            data.add(item);
        }
        //表头(列名)数据
        List<List<String>> head=new ArrayList<>();
        List<String> c1=new ArrayList<>();
        c1.add("姓名");
        List<String> c2=new ArrayList<>();
        c2.add("年龄");
        List<String> c3=new ArrayList<>();
        c3.add("地址");
        head.add(c1);
        head.add(c2);
        head.add(c3);

        Table table=new Table(1);
        table.setHead(head);
        //写入表
        writer.write0(data,sheet,table);
        writer.finish();
    }


    //有映射,有表头
    @Test
    public void withModel() throws FileNotFoundException {
        FileOutputStream out=new FileOutputStream("test2.xls");
        ExcelWriter writer=new ExcelWriter(out,ExcelTypeEnum.XLS);
        //创建sheet,传入StudentModel.class(继承自BaseRowModel)参数设置表头
        Sheet sheet=new Sheet(1,0,StudentModel.class);
        sheet.setSheetName("sheet1");
        //设置写入的数据
        List<StudentModel> data=new ArrayList<>();
        for(int i=0;i<10;i++){
            StudentModel student=new StudentModel();
            student.setName("tom"+i);
            student.setAge("1"+i);
            student.setScore("6"+i);
            data.add(student);
        }
        //写入表
        writer.write(data,sheet);
        writer.finish();
    }
  //映射模型类
static class StudentModel extends BaseRowModel{ @ExcelProperty(value = "姓名",index = 0) private String name; @ExcelProperty(value = "年龄",index = 1) private String age; @ExcelProperty(value = "分数",index = 2) private String score;      //Getter and Setter } }

 @ExcelProperty :映射模型类中使用,用来设置表头索引和名称

 

posted @ 2020-08-24 14:38  hjy1995  阅读(203)  评论(0编辑  收藏  举报