3

i am using following code, for reading a excel using apache poi, its a .xlsx file. Please let me know what i can do, to also alter a value of a cell, in each row as my loop keeps going. Thanks

import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

String fileName = "C:/createCDN.xlsx";
FileInputStream fis = null;
fis = new FileInputStream(fileName);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
FileOutputStream fos=new FileOutputStream(fileName);
XSSFSheet sheet = workbook.getSheetAt(0);
int totalRows=sheet.getLastRowNum();
for(int i=1;i<=totalRows;i++) {
    XSSFRow row = sheet.getRow(i);
    method.fillTextBox(row.getCell(0),"name", pageProp);
    method.fillTextBox(row.getCell(0),"name", pageProp);
} //Do something here, or inside loop to write to lets say cell(2) of same row.

Thanks.

2 Answers 2

14

It should be like this:

for(int i = 1; i <= totalRows; i++) {
    Row row = sheet.getRow(i);
    Cell cell = row.getCell(2);
    if (cell == null) {
        cell = row.createCell(2);
    }
    cell.setCellType(Cell.CELL_TYPE_STRING);
    cell.setCellValue("some value");
}

To save the workbook you could just write:

FileOutputStream fos = new FileOutputStream(fileName);
workbook.write(fos);
fos.close();

You should take a look at POI's Busy Developers' Guide.

4
  • I did that, i think for that I also need to create one fileoutstream, as i only created instream, also after i do all the changes in the cells and loop is over, i need to close the outstream. please suggest, it was giving me error, Oct 5, 2012 at 22:57
  • Thanks, that works.. all i had to is that, but needed to be done, after loop is finished. thanks for the link too, its great. Oct 5, 2012 at 23:06
  • In the Busy Developers Guide they use row.createCell(2).setCellValue( createHelper.createRichTextString("This is a string") ); rather than cell.setCellValue("This is a string");. Anyone know what's going on there?
    – Rory
    Sep 22, 2016 at 11:15
  • @Rory Simple: the first line is for setting "rich text" string value, and the second line is for setting ordinary string value. Sep 26, 2016 at 9:19
1

at first you need to create the space in the excel file, like this:

for(int row = 0; row < 10 ; row++) {
    sheet.createRow(row);
    for(int column = 0; column < 10; column++) { 
        sheet.getRow(row).createCell(column);                
    }                
}            

then you can write the excel using this command:

sheet.getRow(row).getCell(column).setCellValue("hello");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.