[java] easyexcel实现表格数据填充

Easy Excel生成excel

    • 关于EseyExcel:
    • 项目代码
      • 填充对象
      • 数据生成类
      • 主程序类
      • 演示
    • 打包运行
      • 测试
    • 遇到问题

EasyExcel官网

为什么想写这个程序呢?
因为学校要求体温填报为了提高效率所以就有了这个程序
实现功能:根据txt提供的姓名填充当前日期开始5天内的体温信息。

关于EseyExcel:

Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。
easyexcel重写了poi对07版Excel的解析,一个3M的excel用POI sax解析依然需要100M左右内存,改用easyexcel可以降低到几M,并且再大的excel也不会出现内存溢出;03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便

项目代码

创建一个maven项目并引入下面依赖

<dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>3.8.1version>
      <scope>testscope>
    dependency>
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>easyexcelartifactId>
      <version>3.2.1version>
    dependency>
    
    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
      <version>1.18.4version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-simpleartifactId>
      <version>1.7.25version>
      <scope>compilescope>
    dependency>
  dependencies>

填充对象

@ExcelProperty() 注解内的内容和列名相同

{.} :填充list 的时候还要注意 模板中{.} 多了个点 表示list
在这里插入图片描述

@Getter
@Setter
@EqualsAndHashCode
public class DataP {
    @ExcelProperty("学生姓名")
    private String name;
    @ExcelProperty("晨检")
    private double morning;
    @ExcelProperty("午检")
    private double noon;
    @ExcelProperty("晚检")
    private double afternoon;
    @ExcelProperty("异常处置情况")
    private String z;
}

数据生成类

public class DataPadding {
    private static String path = "resources/1.txt";
    /**
     * 生成所有行的数据
     * @return 数据
     * @throws IOException io异常
     */
    public static List<DataP> getDatas() throws IOException {
        List<DataP> data = new ArrayList<>();
        List<String> studentNames = getStudentNames();
        for (String name : studentNames) {
            DataP fillData = getData(name);
            data.add(fillData);
        }
        return data;
    }
    /**
     *  生成一行的数据
     * @param name 姓名
     * @return 数据对象
     */
    public static DataP getData(String name){
        DataP fillData = new DataP();
        fillData.setName(name);
        fillData.setAfternoon(getTemperature());
        fillData.setNoon(getTemperature());
        fillData.setMorning(getTemperature());
        fillData.setZ("无");
        return fillData;
    }
    /**
     *  生成随机体温
     * @return double 体温  区间36.3到36.9
     */
    public static double getTemperature(){
        Random random = new Random();
        DecimalFormat df =new DecimalFormat("#####0.0");
        double n = random.nextDouble()*1.0+36;
        n = Double.valueOf(df.format(n));
        if (n<36.3) n = 36.3;
        if (n == 37) n = 36.8;
        return n;
    }
    /**
     *  读取txt文件获取姓名集合
     * @return 姓名集合
     * @throws IOException io异常
     */
    public static List<String> getStudentNames() throws IOException {
        List<String> list = new ArrayList<>();
        FileInputStream fis = new FileInputStream(path);
        InputStreamReader isr =  new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);
        String line = "";
        while((line = br.readLine()) != null){
           line = new String(line.getBytes(),"utf-8");
          //  System.out.println(line);
            list.add(line);
        }
        br.close();
        isr.close();
        fis.close();
        return list;
    }
    /**
     *  根据日期获取 sheet名
     * @return sheet名  例:3.14
     */
    public static List<String> getTime(){
        List<String> times = new ArrayList<>();
        SimpleDateFormat sdf= new SimpleDateFormat("MM.dd");
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        String time= sdf.format(calendar.getTime());
        times.add(time);
        for (int i = 0; i < 4; i++) {
            calendar.add(calendar.DATE,1);
            time= sdf.format(calendar.getTime());
            times.add(time);
        }
        return times;
    }
    /**
     *  获取填表日期
     * @return 年月日 例:2023/3/14
     */
    public static List<String> getYear(){
        List<String> times = new ArrayList<>();
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy/MM/dd");
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        String time= sdf.format(calendar.getTime());
        times.add(time);
        for (int i = 0; i < 4; i++) {
            calendar.add(calendar.DATE,1);
            time= sdf.format(calendar.getTime());
            times.add(time);
        }
        return times;
    }
}

主程序类

public class App {
    public static void main(String[] args) {
        fillTemplate();
    }
    public static void fillTemplate() {
        //excel模板
        String templateFileName = "resources/计科12学生晨午晚检记录表模板.xlsx";
        File file = new File(templateFileName);
        try (FileInputStream fileInputStream = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
           

            int sheetNum = 5;
            //原模板只有一个sheet,通过poi复制出需要的sheet个数的模板
            XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
            //设置模板的第一个sheet的名称
            List<String> time = DataPadding.getTime();
            workbook.setSheetName(1, time.get(0));
            for (int i = 1; i < sheetNum; i++) {
                //复制模板,得到第i个sheet
                workbook.cloneSheet(1, time.get(i));
            }
            //写到流里
            workbook.write(bos);
            byte[] bArray = bos.toByteArray();
            InputStream is = new ByteArrayInputStream(bArray);
            //输出文件路径
            String fileName = "resources/计科12学生晨午晚检记录表.xlsx";
            ExcelWriter excelWriter = EasyExcel.write(fileName).withTemplate(is).build();
            // 填充到sheet的数据  填表日期
            List<String> year = DataPadding.getYear();
            for (int i = 0; i < sheetNum; i++) {
             // 填充到sheet的数据  行数据
            List list1 = DataPadding.getDatas();
                WriteSheet writeSheet = EasyExcel.writerSheet(time.get(i)).build();
                excelWriter.fill(list1, writeSheet);
                Map<String, String> map = MapUtils.newHashMap();
                map.put("date",year.get(i));
                excelWriter.fill(map, writeSheet);
            }
            // 关闭流
            excelWriter.finish();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

演示

模板

[java] easyexcel实现表格数据填充_第1张图片

打包运行

pom文件添加打包插件

<build>
    <plugins>
      
      <plugin>
        <groupId>org.apache.maven.pluginsgroupId>
        <artifactId>maven-assembly-pluginartifactId>
        <version>2.4.1version>
        <configuration>
          
          <descriptorRefs>
            <descriptorRef>jar-with-dependenciesdescriptorRef>
          descriptorRefs>
          
          <archive>
            <manifest>
              <mainClass>com.hzy.dataPadding.AppmainClass>
            manifest>
          archive>
        configuration>
        <executions>
          <execution>
            <id>make-assemblyid>
            
            <phase>packagephase>
            <goals>
              <goal>singlegoal>
            goals>
          execution>
        executions>
      plugin>
    plugins>
  build>

创建测试目录

[java] easyexcel实现表格数据填充_第2张图片
[java] easyexcel实现表格数据填充_第3张图片

测试

遇到问题

在idea运行正常
[java] easyexcel实现表格数据填充_第4张图片

打包后在windows本地运行会乱码
[java] easyexcel实现表格数据填充_第5张图片

因为中文Windows系统的默认编码格式是GBK,程序会用gbk格式去读utf-8格式的txt文件所以就乱码了。

我们修改代码,读取txt文件时先转化为gbk字节数组再转为utf-8

[java] easyexcel实现表格数据填充_第6张图片

结果如下:

[java] easyexcel实现表格数据填充_第7张图片

我们发现 单数名字乱码 双数名字不乱码 这是因为 utf-8编码格式一个字符3个字节,GBK编码格式一个字符两个字节

测试代码

public class test {
    public static void main(String[] args) throws IOException {
        String path = "1.txt";
        FileInputStream fis = new FileInputStream(path);
        InputStreamReader isr =  new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);
        String line = "";
        System.out.println(Charset.defaultCharset());
        while((line = br.readLine()) != null){
            for(byte b: line.getBytes()){
                System.out.print(b+" ");
            }
            System.out.println();
        	/*这里的代码是下面图里左边才有的
         	for(byte b: line.getBytes("utf-8")){
                System.out.print(b+" ");
            }
            System.out.println();
            System.out.println(line); */
            System.out.println(new String(line.getBytes(),"utf-8"));
        }
        br.close();
        isr.close();
        fis.close();
    }
}

右边边默认编码是utf-8 不会乱码

左边默认编码gbk 以贝利亚为例:

用gbk编码格式读utf-8为:-24 -76 ,-99 -27 ,-120 -87, -28 -70 ,63 。5组 输出乱码,乱码也是5个字

转为utf-8 :-25 -110 -112 ,-26 -65 -122,-27 -97 -124 ,-26 -75 -100 ,-17 -65 -67 。5组 实际上是贝利亚3个字只有3组

我是这么理解的:不一定对

贝利亚正常的utf-8编码是:-24 -76 ,-99 -27 ,-120 -87, -28 -70 ,-102

乱码应该就是用gbk编码格式读utf-8时最后一组差了一个字节系统处理了一下导致乱码
[java] easyexcel实现表格数据填充_第8张图片

最后的解决方法就是启动程序时加上 Dfile.encoding=utf-8

你可能感兴趣的:(小项目,java,excel,开发语言)