将对象集合写入excel并将excel输出(三)

本文介绍如何使用Java将对象集合数据写入Excel文件,并详细讲解了整个过程,包括对象转换、数据填充和文件输出等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>4.1.2</version>
</dependency>
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

将对象写入excel并将excel输出(三)

//将对象信息写入excel表中
    public XSSFWorkbook show1(String oldPath) throws Exception {
        //调用该类中的insertTxts方法,获取对象集合list
        List<ImportTxtEntity> list = insertTxts(oldPath);
        XSSFWorkbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Goods");//创建一张表
        Row titleRow = sheet.createRow(0);//创建第一行,起始为0
        titleRow.createCell(0).setCellValue("序号");//第一行第一列
        titleRow.createCell(1).setCellValue("你的名字");//第一行第二列,以此类推
        titleRow.createCell(2).setCellValue("你的年龄");
        int cell = 1;
        for (ImportTxtEntity importTxtEntity : list) {
            Row row = sheet.createRow(cell);//从第二行开始保存数据
            row.createCell(0).setCellValue(cell);//第二行第一列
            row.createCell(1).setCellValue(importTxtEntity.getName());//第二行第二列,以此类推
            row.createCell(2).setCellValue(importTxtEntity.getAge());
            cell++;
        }
        //返回一个有值的excel表
        return wb;
    }
//这是所有代码的主入口
 public void createExcelOne() throws Exception {
        //这是生成excel文件的名字
        String name = "F:\\Desktop\\a\\帅比.xlsx";
        //这是调用该类中的show1方法生成相应的excel表格,需要传入txt所在的文件夹的位置
        XSSFWorkbook listExcel = show1("D:\\帅比所在的文件夹");
        try{
            // 判断这个文件夹是否存在,如果不存在就生成该文件夹
            File file = new File("F:\\Desktop\\a");
            if(file.exists() || !file.isDirectory()) {
                file.mkdirs();
            }
            //将调用show1方法生成的文件夹进行输出到指定位置
            FileOutputStream outputStream = new FileOutputStream(new File(name));
            listExcel.write(outputStream);
            //关闭输出流
            outputStream.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值