writing a new cell to a sheet apache poi

十年热恋 提交于 2021-01-27 16:47:03

问题


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.


回答1:


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.




回答2:


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");


来源:https://stackoverflow.com/questions/12754641/writing-a-new-cell-to-a-sheet-apache-poi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!