Java怎么将数据写入Excel

Java怎么将数据写入Excel


上一篇是java怎么读取Excel表数据

个人把这个方法封装了WriteToExcel

public class WriteToExcel {

    private static XSSFWorkbook workbook;
    private static XSSFSheet sheet;
    private static XSSFRow row;
    private static XSSFCell cell;
    private static File file;

    //创建sheet页
    public static void setSheet(String sheetName) {
        workbook = new XSSFWorkbook();
        sheet = workbook.createSheet(sheetName);
    }
    //创建表头
    public static void createHead(List<String> headList) {
        //创建表头,也就是第一行
        row = sheet.createRow(0);
        for (int i = 0; i < headList.size(); i++) {
            cell = row.createCell(i);
            cell.setCellValue(headList.get(i));
        }
    }
    //创建表内容
    public static void createContent(List<List<String>> contentList) {
        //创建表内容,从第二行开始
        for (int i = 0; i < contentList.size(); i++) {
            row = sheet.createRow(i + 1);
            for (int j = 0; j < contentList.get(i).size(); j++) {
                row.createCell(j).setCellValue(contentList.get(i).get(j));
            }
        }
    }
    //写入文件
    public static void writeToFile(String filePath){
        file = new File(filePath);
        //将文件保存到指定的位置
        try {
            workbook.write(new FileOutputStream(file));
            System.out.println("写入成功");
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 内容测试数据
    protected static List<List<String>> getContent() {
        List<List<String>> contentList = new ArrayList<>();
        List<String> content1 = new ArrayList<>();
        content1.add("张三");
        content1.add("18");
        List<String> content2 = new ArrayList<>();
        content2.add("李四");
        content2.add("20");
        contentList.add(content1);
        contentList.add(content2);
        return contentList;
    }
    
    public static void main(String[] args) {
        //表头测试数据
        List<String> headList = new ArrayList<>();
        headList.add("昵称");
        headList.add("年龄");
        List<List<String>> contentList = getContent();//内容测试数据

        setSheet("WorkSheet");                        //创建sheet页
        createHead(headList);                         //设置表头
        createContent(contentList);                   //设置内容
        writeToFile("D://work.xls");         //写入文件
    }
}

总结

这其中还有一些设置表格的方法,但是个人认为在此处设置样式没啥太大意义,可以直接在生成的excel表里直接设置,代码设置的话不灵活,如果还是想添加样式的话可以以此为模板再从中设置一些样式方法,这与我的模板并不冲突

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

芝士炸香蕉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值