Java 将新单元格写入工作表apache poi

Java 将新单元格写入工作表apache poi,java,selenium,junit,apache-poi,Java,Selenium,Junit,Apache Poi,我使用以下代码,用于使用ApachePOI读取excel,它是一个.xlsx文件。请让我知道我能做些什么,在循环继续进行的过程中,在每一行中修改一个单元格的值。谢谢 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;

我使用以下代码,用于使用ApachePOI读取excel,它是一个.xlsx文件。请让我知道我能做些什么,在循环继续进行的过程中,在每一行中修改一个单元格的值。谢谢

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.
import java.io.FileInputStream;
导入org.apache.poi.ss.usermodel.Cell;
导入org.apache.poi.xssf.usermodel.XSSFRow;
导入org.apache.poi.xssf.usermodel.xssfheet;
导入org.apache.poi.xssf.usermodel.xssf工作簿;
String fileName=“C:/createCDN.xlsx”;
FileInputStream fis=null;
fis=新文件输入流(文件名);
XSSF工作簿=新XSSF工作簿(fis);
FileOutputStream fos=新的FileOutputStream(文件名);
XSSFSheet sheet=workbook.getSheetAt(0);
int totalRows=sheet.getLastRowNum();

对于(int i=1;i它应该是这样的:

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");
}
for(int row = 0; row < 10 ; row++) {
    sheet.createRow(row);
    for(int column = 0; column < 10; column++) { 
        sheet.getRow(row).createCell(column);                
    }                
}            

您应该看看。

首先需要在excel文件中创建空间,如下所示:

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");
}
for(int row = 0; row < 10 ; row++) {
    sheet.createRow(row);
    for(int column = 0; column < 10; column++) { 
        sheet.getRow(row).createCell(column);                
    }                
}            

我这样做了,我想我还需要创建一个fileoutstream,因为我只创建了instream,而且在我对单元格进行了所有更改并且循环结束后,我需要关闭outstream。请建议,这给了我错误,谢谢,这是可行的。我所需要做的就是,但需要在循环完成后完成。也感谢链接,这是非常有用的很好。在《忙碌的开发人员指南》中,他们使用
row.createCell(2).setCellValue(createHelper.createRichTextString(“这是一个字符串”);
而不是
cell.setCellValue(“这是一个字符串”);
。有人知道这是怎么回事吗?@Rory Simple:第一行是设置“富文本”字符串值,第二行用于设置普通字符串值。