我正在尝试将所有内容从一个excel文件表追加到另一个excel文件表。一切正常,除了单元格的格式。

为了从原始的excel文件中获取相同的格式,我使用了HSSFCellStyle

这是我的代码:

私人声明:

private HSSFRow row1;
private HSSFCell cell1;
private HSSFCellStyle cellStyle1;
private FileInputStream inFile1,inFile2;
private HSSFSheet excelSheet1=null,excelSheet2=null;
private HSSFWorkbook excelBook1=null,excelBook2=null;


主要方法:

public static void main(String args[]){
    appendToExcelClass test = new appendToExcelClass();
    test.appendToExcel(new File("C:\\excel1.xls"),new File("C:\\excel2.xls"));
}


附加内容的方法:

public void appendToExcel(File file1,File file2){
    try{
        if(file1.exists() && file2.exists()){
            inFile1 = new FileInputStream(file1);
            inFile2 = new FileInputStream(file2);
            excelBook1 = new HSSFWorkbook(inFile1);
            excelBook2 = new HSSFWorkbook(inFile2);
            excelSheet1 = excelBook1.getSheetAt(0);
            excelSheet2 = excelBook2.getSheetAt(0);
            Iterator rowIter = excelSheet2.rowIterator();
            while(rowIter.hasNext()){
                HSSFRow myRow = (HSSFRow) rowIter.next();
                Iterator cellIter = myRow.cellIterator();
                List<String> cellStoreVector;
                cellStoreVector = new ArrayList<>();
                while(cellIter.hasNext()){
                    HSSFCell myCell = (HSSFCell) cellIter.next();
                    String cellvalue = myCell.getStringCellValue();
                    cellStyle1 = myCell.getCellStyle();  /*The problem is in this part, I think I didn't get well how get the cell's format*/
                    cellStoreVector.add(cellvalue);
                }
                row1 = excelSheet1.createRow(excelSheet1.getLastRowNum()+1);
                cell1 = row1.createCell(0);
                cell1.setCellStyle(cellStyle1);  /*At the moment to execute this part, it throws this: This Style does not belong to the supplied Workbook. Are you trying to assign a style from one workbook to the cell of a different workbook?*/
                cell1.setCellValue(cellStoreVector.get(0).toString());
            }
            FileOutputStream outFile1 = new FileOutputStream(file1);
            excelBook1.write(outFile1);
            outFile1.close();
        }
    }catch(Exception ex){
        ex.printStackTrace();
    }
}


我不确定引发错误的部分。

预先,谢谢。

最佳答案

错误消息几乎可以解释问题。 HSSFWorkbook包含一个可以使用的所有样式的表。每当调用setCellStyle时,传递的HSSFCellStyle必须在该表中。发生的是,您从excelBook2的单元格中提取的HSSFCellStyle在excelBook1中不存在。

要解决此问题,您可以调用excelBook1.createCellStyle来创建新样式,并从提取的样式中克隆其属性。这是如何执行此操作的示例。

HSSFCellStyle newStyle = excelBook1.createCellStyle();
newStyle.cloneStyleFrom(cellStyle1);

关于java - 使用格式从Excel文件获取单元格值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20847731/

10-10 18:52