I'm starting to do a new process to add rows from an excel file to another excel file, in other words: append rows to an existing excel sheet.
To make that, I was testing the following code, based in a code that I found on Internet:
Private global declarations:
private HSSFRow row;
private HSSFCell cell;
private FileInputStream inFile;
private POIFSFileSystem poiFile;
private HSSFSheet excelSheet = null;
private HSSFWorkbook excelBook = null;
private FileOutputStream outFile = null;
private static String outputFileName;
I start everything with the main method:
public static void main(String args[]){
outputFileName = "C:\\test1.xls";
List<String> newContent = new ArrayList<>();
newContent.add("Test Val1");
newContent.add("Test Val2");
newContent.add("Test Val3");
testingClass test = new testingClass();
test.overwriteExcel(outputFileName,newContent);
}
With this I created the file, and with the same I pretend update it:
public void overwriteExcel(String outputFileName, List<String> newContent){
try{
if(new File(outputFileName).exists()){ //--If the file exists/is already created
outFile = new FileOutputStream(new File(outputFileName),true); /*With the "true" parameter, the change must been applied but, nothing happens...*/
inFile = new FileInputStream(new File(outputFileName));
poiFile = new POIFSFileSystem(inFile);
excelBook = new HSSFWorkbook(poiFile);
excelSheet = excelBook.getSheetAt(0);
}else{ //--Create the file
outFile = new FileOutputStream(new File(outputFileName));
excelBook = new HSSFWorkbook();
excelSheet = excelBook.createSheet("Sheet1");
}
int i = 0;
for(Iterator iter = newContent.iterator(); iter.hasNext();){
Object val = iter.next();
if(val!=null){
row = excelSheet.createRow(excelSheet.getLastRowNum()+1);
cell = row.createCell(0); //--Temporaly, I change this val manually
cell.setCelval(newContent.get(i++));
}
}
excelBook.write(outFile);
outFile.flush();
outFile.close();
}catch(Exception ex){
JOptionPane.showMessageDialog(null,"Error: "+ex.getMessage(),"Warning!",JOptionPane.ERROR_MESSAGE);
}
}
When the class ends his process, I saw the file and I can perceive the file size change, but when I open it, everything is the same, after I close the file, this returns to his previous size...
Trying to understand what happens, I changed the "0" by "1" in row.createCell(0), I delete the file and repeat the process, everything right, but after when I change the value again to "0", changes hasn't been applied... I don´t know if it's some file permissions...
I think there's something wrong with the code, this isn't the first time that I work with excel files, but it's the first time that I'm trying to modified it.
In advance, thanks!!!