JAVA导出EXCEL的方法

首先是MAVEN依赖


<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>


注意poi为XSL格式(03以及03以前)  poi-ooxml为07以后的XLSX


 public static void writeCountryListToFile(String fileName, ArrayList<ArrayList<String>> countryList) throws Exception{
        //首先创建工作表
        Workbook workbook = null;

        //随便初始化个数据
        ArrayList<String> l1 = new ArrayList<>();
        l1.add("广东"); l1.add("广州");
        countryList.add(l1);

        ArrayList<String> l2 = new ArrayList<>();
        l2.add("福建"); l2.add("福州");
        countryList.add(l2);

        //判断文件的结尾名称来创建不同格式的文件
        if(fileName.endsWith("xlsx")){
            workbook = new XSSFWorkbook();
        }else if(fileName.endsWith("xls")){
            workbook = new HSSFWorkbook();
        }else{
            throw new Exception("invalid file name, should be xls or xlsx");
        }

        //创建一个sheet 名字随便起
        Sheet sheet = workbook.createSheet("SomeThing");

        int rowIndex = 0;
        for (int i=0;i<countryList.size();i++)
        {
            List<String> ll= countryList.get(i);
            //创建一行
            Row row = sheet.createRow(i);
            for (int j=0; j<ll.size();j++)
            {
                //创建一行的某个cell    定位(i,j) 和table的使用方式差不多
                Cell cell = row.createCell(j);
                cell.setCellValue(ll.get(j));
            }
        }


        //定义输出流,将workbook输出到文件 结束
        FileOutputStream fos = new FileOutputStream(fileName);
        workbook.write(fos);
        fos.close();
        System.out.println(fileName + " written successfully");
    }

完~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值