简体   繁体   English

excel,Apache Poi,无法写入单元格

[英]excel, Apache Poi, unable to write to cell

I have been given a project which requires me to extract information from an excel file, do some calculations on the data and write the information back to an excel sheet. 我得到了一个项目,该项目需要我从excel文件中提取信息,对数据进行一些计算,然后将信息写回到excel工作表中。 for some reason a part of my data just does feed into the cells. 由于某种原因,我的一部分数据确实会馈入单元格中。 AN example is given below. 下面给出一个例子。

package ExcelDocs;

import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;

public class Trial{

    public static void main(String[] agrs){

        Workbook wb=new XSSFWorkbook();
        Sheet ws=wb.createSheet("Testing");
        Cell c1=ws.createRow(0).createCell(0);
        c1.setCellValue("hello");
        Cell c2=ws.createRow(1).createCell(1);
        c2.setCellValue("how are you?");
        for(int i=1;i<7;i++){
            Cell c3=ws.createRow(i).createCell(0);
            c3.setCellValue(i);
        }

        try{ 
            FileOutputStream out=new FileOutputStream("ANISH.xlsx");
            wb.write(out);
            out.close();
        } catch(Exception e){
            System.out.println("unable to write to excel");
        }

    }
}

This code should generate the following output: 此代码应生成以下输出:

      COL1     COL2
ROW1  hello
ROW2           how are you?
ROW3
ROW4
ROW5
ROW6
ROW7

instead I get this as the output 相反,我得到这个作为输出

      COL1     COL2
ROW1  hello
ROW2           
ROW3
ROW4
ROW5
ROW6
ROW7

can anyone tell me why the "how are you?" 谁能告诉我为什么“你好吗?” is getting deleted? 被删除? I facing the same problem in my other programs too. 我在其他程序中也遇到相同的问题。

该行被for循环中的行覆盖:

Cell c2=ws.createRow(1).createCell(1);

That's because you're overwriting the row created at index 1 in this for loop. 那是因为您要覆盖此for循环中在索引1处创建的行。

for(int i=1;i<7;i++){ // when i = 1
    Cell c3=ws.createRow(i).createCell(0); // it recreates a row at that index
    c3.setCellValue(i); // and re-writes it here in the loop.
}

You need to change the loop to start creating rows from the index 2. 您需要更改循环才能从索引2开始创建行。

for(int i=2; i<7; i++) { // now it starts from row index 2 and doesn't overwrite your previous row created at index 1
    Cell c3=ws.createRow(i).createCell(0); 
    c3.setCellValue(i);
}

In your for loop the createRow is trashing the row that you created before. for循环中, createRow破坏了之前创建的行。

So, before the loop, when you do Cell c2=ws.createRow(1).createCell(1); 因此,在循环之前,执行Cell c2=ws.createRow(1).createCell(1); change this so that the Row object is saved. 更改此设置,以便保存Row对象。

Row r = Cell c2=ws.createRow(1);
r.createCell(1);

and use r in your loop too. 并在循环中也使用r

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM