用Java给excel里面连续写数据!

前几天,我在用Java给excel里写数据时,发现只能写最后一个数据,经过很久的思考与调试,最终终于知道了问题的所在。
先来看一下出错的代码:

public static void xlsOutput(int rows,int columns,String str,String outputUrl) {
        // rows是要写的行数
        //columns是要写的列数
        //str是要写的数据
        //outputUrl是要写的路径
        try {
            FileOutputStream fop=new FileOutputStream(outputUrl);
            HSSFWorkbook wb =new HSSFWorkbook();
            Sheet sheet=wb.createSheet();
            Row row=sheet.createRow(rows);
            row.createCell(columns).setCellValue(str);
            wb.write(fop);
            fop.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

public class MyTest3 {
    public static void main(String[] args) {
        String outputUrl="C:\\Users\\陈庚\\Desktop\\excel表格\\ranking.xls";
        XLS.xlsOutput(0,0,"1000",outputUrl);
        XLS.xlsOutput(1,0,"1000",outputUrl);
        XLS.xlsOutput(2,0,"1000",outputUrl);
        XLS.xlsOutput(3,0,"1000",outputUrl);
    }
}


在这里插入图片描述
这是之前的结果,这里就出错在我们每次写数据时就会使用new HSSFWorkbook()新创建一个工作簿,然后在新的工作簿里写数据,最后当然只保留最后一次写的数据,因为前面的都被覆盖了。

怎么去解决这个问题呢?我们应该利用读的方式读取到行,这样我们每次根据路径读的时候,就读的是一个工作簿了,利用读的方式拿到行,然后我们在行对应的列去写东西即可,这样就不会出错。

看一下源代码:

public static void xlsOutput(int rows, int columns, String str, String outputUrl) throws Exception {
       File file = new File(outputUrl);
       Workbook wb;
       Sheet sheet;
       Row row;
       if (file.exists()) {
           FileInputStream fip = new FileInputStream(outputUrl);
           wb = WorkbookFactory.create(fip);
           sheet = wb.getSheetAt(0);
           if(rows>sheet.getLastRowNum()){
               row = sheet.createRow(rows);
           }else {
               row = sheet.getRow(rows);
           }
           fip.close();
       } else {
           wb = new HSSFWorkbook();
           sheet = wb.createSheet();
           row = sheet.createRow(rows);
       }
       HSSFCell cell = (HSSFCell) row.createCell(columns);
       cell.setCellType(CellType.STRING);
       cell.setCellValue(str);

       FileOutputStream fop = new FileOutputStream(outputUrl);
       wb.write(fop);
       fop.close();
   }

我们测试一下:
在这里插入图片描述
这样的结果就正确了!

在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值