Java如何利用poi创建excel并写入数据

该部分主要是在做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();
        }

    }

如果你想开发小程序或者app的话,可以通过第三方专业开发平台,来帮助你实现开发需求:厦门在乎科技-专注厦门小程序开发、app开发、网站开发

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值