I'm trying to append all the content from an excel file sheet to another excel file sheet. Everything is ok, excepting the cell's format.
To take the same format from the original excel file, I'm using HSSFCellStyle.
This is my code:
Private declarations:
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;
Main method:
public static void main(String args[]){
appendToExcelClass test = new appendToExcelClass();
test.appendToExcel(new File("C:\\excel1.xls"),new File("C:\\excel2.xls"));
}
Method to append the content:
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();
}
}
I'm not sure with the part that throws me the error.
In advance, thanks.