jxl写入excel表格为空

今天要用java创建一个excel,并把解析的数据存放到excel表中,但是表中一直是空,写不进数据,程序横看竖看都没有问题,下面举一个简单的例子。关于jxl的使用,请参考此篇文章

首先引出jxl写数据为空的例子

    public static void main(String[] args) throws IOException, RowsExceededException, WriteException {
        /*创建表*/
        WritableWorkbook book = Workbook.createWorkbook(new File("E:/MyData/test.xls"));
        /*创建sheet页*/
        WritableSheet sheet = book.createSheet("第一页", 0);
        Person person = new Person();
        person.setUserid("11111");
        /*把2行5列数据写入excel,写的是第一行和第二行*/
        for(int i=0; i<2; i++){
            for(int j=0; j<5; j++){
                sheet.addCell(new Label(j, i, "data" + i + j));
            }
        }
        /*第一次把上面2行5列数据写入excel*/
        book.write(); //1、此地非常重要,千万不要加

        /*继续把2行5列数据写入excel,写的是第三行和第四行*/
        for(int i=2; i<4; i++){
            for(int j=0; j<5; j++){
                sheet.addCell(new Label(j, i, "data" + i + j));
            }
        }
        /*第二次把第三行和第四行数据写入excel*/
        book.write(); //2
        book.close();
    }

运行程序,excel数据如下
这里写图片描述
上面示例总共写了两批数据,第一次写入了第一行和第二行的5列数据,然后调用了book.write();再当继续写入第三行和第四行数据时就已经不管用了,因为当第一次调用book.write()后,表示数据已经写完了,后面添加的数据就不会再写进去,即使后面又调用了book.write()。所以要在调用book.write()之前,把数据准备好,然后一次性写入。正确写法改成如下
删掉第一个book.write()

    public static void main(String[] args) throws IOException, RowsExceededException, WriteException {
        WritableWorkbook book = Workbook.createWorkbook(new File("E:/MyData/test.xls"));
        WritableSheet sheet = book.createSheet("第一页", 0);
        Person person = new Person();
        person.setUserid("11111");
        for(int i=0; i<2; i++){
            for(int j=0; j<5; j++){
                sheet.addCell(new Label(j, i, "data" + i + j));
            }
        }
        //book.write();应删掉此句代码
        sheet = book.getSheet("第一页");
        for(int i=2; i<4; i++){
            for(int j=0; j<5; j++){
                sheet.addCell(new Label(j, i, "data" + i + j));
            }
        }
        book.write();
        book.close();
    }

运行程序,写入excel数据如下:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/u010502101/article/details/80658297