如何使用poi和for循环在同一个excel中读取和写入数据

时间:2015-12-24 07:41:06

标签: java apache-poi

我正在使用以下代码来读/写,.. 我能够读取数据,但无法在其中写入数据。

 public class RWExcelPOI {
    File src=new File("D:\\Sujit\\Automated Script\\Auto_Tuto\\TestDataPOI.xlsx");
    XSSFWorkbook wb;
    XSSFSheet Sheet1;
    FileOutputStream fileOut;

    public void ReadExcel1() throws Exception{


        FileInputStream fis = new FileInputStream(src);

        XSSFWorkbook wb=new XSSFWorkbook(fis);

        XSSFSheet Sheet1=wb.getSheetAt(0);


        int rowcount=Sheet1.getPhysicalNumberOfRows();
        int colcount=Sheet1.getRow(0).getPhysicalNumberOfCells();
        System.out.println("Total Number of Rows is ::"+rowcount);
        System.out.println("Total number of Col is ::"+colcount);

        for(int i=0;i<rowcount;i++){


            for(int j=0;j<colcount;j++){


                String testdata1=Sheet1.getRow(i).getCell(j).getStringCellValue();
                System.out.println("Test data from excel cell  :"+testdata1);
                wb.close();


                Cell cell = null;  
                cell = Sheet1.getRow(i).getCell(j);

                cell.setCellValue("hmm");
                // Write the output to a file  
                FileOutputStream fileOut = new FileOutputStream(src);  
                wb.write(fileOut); 

            }

        }


    }

    public static void main(String args[]) throws Exception{

        RWExcelPOI read=new RWExcelPOI();
        read.ReadExcel1();



    }

请告诉我我失踪的地方。 我的Excel表格就像

用户1 pswd 1(我想写这个专栏) 用户2 pswd 2(我想写在这一栏)

当我运行我的代码时,我的输出如下: 用户1 pswd 1 用户2 pswd 2

但是当我打开它时会覆盖以前的数据

1 个答案:

答案 0 :(得分:0)

乍一看,你的wb1没有传递给它的文件。另外,你关闭wb,这是Sheet1和row都来自的对象,因此如果wb关闭且wb1没有文件,你就不能用它们来写。