使用POI将数据写入xlsx文件时遇到麻烦Apache – Excel之后会损坏

我已经删除了很多代码,主要是试图捕获块,并粘贴在这里,我相信这很容易让你看,并build议我解决我所面临的问题。 我在SoapUI工具的Groovy Script步骤中运行下面的脚本。 大部分variables数据types遵循Groovy语言语法。

当我运行这个代码时,会创build一个带有destPathvariables中提到的文件名的xlsx文件,但其大小为0 KB。 当我试图打开文件时,由于文件格式或文件扩展名无效,我看到“Excel无法打开文件的文件名”消息,请确认文件没有被破坏,文件的扩展名与文件。” 我看不出我在哪里犯错。

def srcPath = "C:\\Test Data\\Test Data2.xlsx" def destPath = "C:\\Test Data\\Results\\destSheet.xlsx" def setData = new SetData(log,srcPath,destPath) log.info setData.setCellData("Result",0,"Testing123") class SetData{ def log; //log variable to print values on the console String srcPath; String destPath; XSSFWorkbook workbook; OPCPackage pkg; SetData(log,srcPath,destPath){ this.log = log; this.srcPath =srcPath; this.destPath = destPath} public String setCellData(String colName,int rowNum, String data){ OPCPackage pkg = OPCPackage.open(srcPath); Workbook workbook = WorkbookFactory.create(pkg); if(rowNum<0) return "false"; int colNum=-1; XSSFSheet sheet = workbook.getSheetAt(0); XSSFRow row=sheet.getRow(0); for(int i=0;i<row.getLastCellNum();i++){ if(row.getCell(i).getStringCellValue().trim().equals(colName)) colNum=i; } sheet.autoSizeColumn(colNum); row = sheet.getRow(rowNum+1); log.info "Row data " + row //log.info is equivalent to System.out.Println in Java,to print values on the console. XSSFCell cell = row.getCell(colNum); // cell style CellStyle cs = workbook.createCellStyle(); cs.setWrapText(true); cell.setCellStyle(cs); log.info data; //prints Testing123 cell.setCellValue(data); // Set the cell data log.info "raw cell Value" + "***" + cell.getRichStringCellValue().getString() //Prints "Testing123" log.info "Column index "+ cell.getColumnIndex() // Prints 3 log.info cell.getRowIndex() // Prints 0 fileOut = new FileOutputStream(new File(destPath)); workbook.write(fileOut); fileout.flush(); fileOut.close(); fileOut=null; pkg.close() return "true"; } 

看起来像你的混合XSSFWorkbook和工作簿。 你还应该检查你的源文件中的行和单元格是否实际上有这些行/单元格,如果没有,就创build它们。 下面是您的代码的简化版本,用于从其他工作簿创buildExcel工作簿并写入该工作簿:

  String srcPath = "C:\\projects\\source.xlsx"; String destPath = "C:\\projects\\destSheet.xlsx"; XSSFWorkbook workbook = (XSSFWorkbook)WorkbookFactory.create(new File(srcPath)); XSSFSheet sheet = workbook.getSheetAt(0); XSSFRow row = sheet.getRow(1); if(row == null) { row = sheet.createRow(1); } XSSFCell cell = row.getCell(0); if(cell == null) { cell = row.createCell(0); } cell.setCellValue("Testing123"); FileOutputStream fileOut = new FileOutputStream(new File(destPath)); workbook.write(fileOut); fileOut.flush(); fileOut.close();