将新单元格写入工作表 apache poi [英] writing a new cell to a sheet apache poi
本文介绍了将新单元格写入工作表 apache poi的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下代码,用于使用 apache poi 读取 excel,它是一个 .xlsx 文件.请让我知道我能做什么,在我的循环继续进行时,在每一行中更改单元格的值.谢谢
import java.io.FileInputStream;导入 org.apache.poi.ss.usermodel.Cell;导入 org.apache.poi.xssf.usermodel.XSSFRow;导入 org.apache.poi.xssf.usermodel.XSSFSheet;导入 org.apache.poi.xssf.usermodel.XSSFWorkbook;String fileName = "C:/createCDN.xlsx";FileInputStream fis = null;fis = new FileInputStream(fileName);XSSFWorkbook 工作簿 = 新 XSSFWorkbook(fis);FileOutputStream fos=new FileOutputStream(fileName);XSSFSheet sheet = workbook.getSheetAt(0);int totalRows=sheet.getLastRowNum();for(int i=1;i<=totalRows;i++) {XSSFRow 行 = sheet.getRow(i);method.fillTextBox(row.getCell(0),"name", pageProp);method.fillTextBox(row.getCell(0),"name", pageProp);}//在这里做一些事情,或者在循环内写入让我们说同一行的单元格(2).
谢谢.
解决方案
应该是这样的:
for(int i = 1; i <= totalRows; i++) {行行 = sheet.getRow(i);单元格单元格 = row.getCell(2);如果(单元格 == 空){单元格 = row.createCell(2);}cell.setCellType(Cell.CELL_TYPE_STRING);cell.setCellValue("某个值");}
要保存工作簿,您只需编写:
FileOutputStream fos = new FileOutputStream(fileName);工作簿.写(fos);fos.close();
您应该查看POI 的繁忙开发人员指南..>
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.
解决方案
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.
这篇关于将新单元格写入工作表 apache poi的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文