使用Apache POI将数据写入xlsx文件时遇到问题 - 之后Excel会损坏

时间:2015-06-18 10:38:47

标签: java excel apache-poi soapui xssf

我删除了很多代码,主要是try-catch块并粘贴在这里,我认为很容易让你看到并建议我解决我面临的问题。我在SoapUI工具的Groovy脚本步骤中运行以下脚本。大多数变量数据类型遵循Groovy语言语法。

当我运行此代码时,会创建一个带有文件名的xlsx文件,该文件名在destPath变量中,但大小为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";
}

1 个答案:

答案 0 :(得分:1)

看起来像是在混合XSSFWorkbook和Workbook。您还应该检查您从源文件中读取的行和单元格是否实际上具有这些行/单元格,如果它们不是,则创建它们。这是用于从其他工作簿创建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();