[英]Unable to write in an empty row in Excel using Apache POI
Excel 格式-.xls
我正在尝试将值从一张 Excel 表复制/粘贴到另一张现有的 Excel 表中。 我无法在空行中写入值。 如果 Excel 行有一些值,那么它正在更新。 请检查下面的代码。
我的代码:
FileInputStream file = new FileInputStream(new File(strWorkBookName));
HSSFWorkbook strWorkBook = new HSSFWorkbook(file);
HSSFSheet sheet = strWorkBook.getSheet(sheetName);
// Retrieve the row and check for null
HSSFRow sheetrow = sheet.getRow(rowNo);
if(sheetrow == null){
logger.info("CREATING ROW"+rowNo);
sheetrow = sheet.createRow(rowNo);
}
// Update the value of a cell
HSSFCell cell = sheetrow.getCell(columnNo);
if(cell == null){
logger.info("CREATING COLUMN " + columnNo);
cell = sheetrow.createCell(columnNo); }
cell.setCellValue(valueToUpdate);
FileOutputStream outFile = new FileOutputStream(new File(strWorkBookName));
strWorkBook.write(outFile);
outFile.close();
如果现有的 Excel 文件正在更新,您确定您正在正确验证吗?
您忘记关闭Workbook
object,但您的代码对我来说仍然是一种魅力。 这是我测试过的工作代码(适用于全行和空行):
public static void main(String[] args) throws IOException {
int sheetPosition = 0;
int rowPosition = 100;
int cellPosition = 100;
String excelFilePath = "D:\\Desktop\\testExcel.xls";
FileInputStream fileInputStream = new FileInputStream(new File(excelFilePath));
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = workbook.getSheetAt(sheetPosition);
HSSFRow sheetrow = sheet.getRow(rowPosition);
if (sheetrow == null){
System.out.println("new row at position " + rowPosition);
sheetrow = sheet.createRow(rowPosition);
}
HSSFCell cell = sheetrow.getCell(cellPosition);
if(cell == null){
System.out.println("new cell (for row " + rowPosition + ") at position " + cellPosition);
cell = sheetrow.createCell(cellPosition);
}
cell.setCellValue("New Amazing Value!");
FileOutputStream outFile = new FileOutputStream(new File(excelFilePath));
workbook.write(outFile);
outFile.close();
workbook.close(); // <-- Do not forget that!
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.