我删除了很多代码,主要是try-catch块,并粘贴在这里,我相信这些代码很容易让您查看,并建议我解决我面临的问题。我在SoapUI工具中的Groovy脚本步骤中运行以下脚本。大多数变量数据类型都遵循Groovy语言语法。
当我运行这段代码时,创建了一个文件名在destPath变量中的xlsx文件,但大小为0KB。当我尝试打开该文件时,看到消息"Excel无法打开文件“"filename”,因为文件格式或文件扩展名无效。请验证该文件是否已损坏,以及该文件扩展名是否与该文件的格式匹配。我看不出哪里出了错。
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";
}发布于 2015-06-23 10:53:57
看起来你混合了XSSFWorkbook和工作簿。您还应该检查从源文件中读取的行和单元格是否确实包含这些行/单元格,如果没有,则创建它们。下面是用于从另一个工作簿创建Excel工作簿并将其写入的代码的简化版本:
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();https://stackoverflow.com/questions/30913050
复制相似问题