关于java:Java如何利用poi创建excel并写入数据看这篇就够啦~

7次阅读

共计 3025 个字符,预计需要花费 8 分钟才能阅读完成。

作者:悠悠做神仙

起源:恒生 LIGHT 云社区

该局部次要是在做 testNG 数据驱动时候的一个需要,然而写入 excel 其实利用场景很多,大家能够参考一下演示代码。其实,除了利用 POI 写入 excel,还能够思考 csv 文件写入,文章中也写了一个工具类可供参考。

1、利用 POI 创立 excel 写入数据

首先,导入依赖,在 pom 文件减少以下依赖:

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.8</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.5</version>
    </dependency>

上面都是用的 XSSF 结尾的类,文件后缀为“.xlsx”
(HSSF 结尾的类对应文件后缀为“.xls”)
留神:因为整体架构须要,所以每个项都建了一个汇合,这个依据理论须要也能够建一个类的汇合。

上代码:

/**
 * @author youyouzuoshenxian
 * @version 1.0.0
 * @ProjectName demoProject
 * @ClassName MyTest.java
 * @Description 利用 Poi 生成 excel
 * @param filePath
 * @createTime 2021 年 07 月 25 日 18:25:00
 */
public static void getExcel(String filePath){ 
   // 定义表头
    String[] title = {"理论后果", "预期后果", "形容"};
    // 定义理论后果集
    // List<Object[]> data = new ArrayList<>();
    // data.add(new Object[]{"页面元素 1", "页面元素 2", "case1"});
    // data.add(new Object[]{"悠悠做神仙", "小神仙", "case2"});
    List<String> actuallist = new ArrayList<>();
    List<String> exceptlist = new ArrayList<>();
    List<String> description = new ArrayList<>();
    actuallist.add("登录 admin");
    actuallist.add("yyzsx");
    actuallist.add("悠悠做神仙");

    exceptlist.add("登录");
    exceptlist.add("youyouuzoshenxian");
    exceptlist.add("悠悠");

    description.add("case1");
    description.add("case2");
    description.add("case3");

    // 创立 excel 工作簿
    XSSFWorkbook workbook = new XSSFWorkbook();
    // 创立工作表 sheet
    XSSFSheet sheet = workbook.createSheet();
    // 创立第一行
    XSSFRow row = sheet.createRow(0);
    XSSFCell cell = null;
     // 插入第一行的表头
    for (int i = 0; i < title.length; i++) {cell = row.createCell(i);
        cell.setCellValue(title[i]);
    }
       for (int i = 1; i <actuallist.size()+1; i++) {XSSFRow nrow = sheet.createRow(i);
        XSSFCell ncell = nrow.createCell(0);
        ncell.setCellValue(actuallist.get(i-1));
        ncell=nrow.createCell(1);
        ncell.setCellValue(exceptlist.get(i-1));
        ncell=nrow.createCell(2);
        ncell.setCellValue(description.get(i-1));
    }
    // 创立 excel 文件 
    // 这里的门路就是我的项目下的 resources 文件夹外面 filePath
    //filePath=./src/main/resources/testdata.xlsx
     File file=new File(filePath);
    try {System.out.println(file.getCanonicalPath());
        file.createNewFile();
        // 将 excel 写入
        FileOutputStream stream= FileUtils.openOutputStream(file);
        workbook.write(stream);
        stream.close();} catch (IOException e) {e.printStackTrace();
    }
}

调用办法,看一下执行后果:

2、写入 csv 文件工具类

 /**
 * @author youyouzuoshenxian
 * @version 1.0.0
 * @ProjectName demoProject
 * @ClassName MyTest.java
 * @Description 利用 Poi 生成 excel
 * @param filePath
 * @param header
 * @param info
 * @createTime 2020 年 08 月 25 日 20:05:13
 */
 public static void writeCVS(String filePath, String header, List<String> info) {
        BufferedWriter fw = null;
//        String header = "method,code,javaPath\r\n";
        try {fw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (filePath,true),"GBK"));
            StringBuilder str =null;
            fw.write(header);
            for (int i = 0, lenth = info.size(); i < lenth; i++) {str = new StringBuilder();
                String src = info.get(i);
                String[] colum = src.split("@");
                for (int j = 0, len = colum.length; j < len; j++) {String infoitem = colum[j];
                    if (infoitem.contains(",")) {if (infoitem.contains("\"")) {infoitem = infoitem.replace("\"", "\"\"");
                        }
                        infoitem = "\"" + infoitem + "\"";
                    }
                    str.append(infoitem + ",");
                }
                if(!StringUtils.isBlank(str.toString())){fw.write(str.toString());
                }
                fw.flush();}
            fw.close();} catch (IOException e) {e.printStackTrace();
        }

    }

心愿大家有所播种!

正文完
 0