You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@poi.apache.org by hbagchi <hb...@yahoo.com> on 2007/03/12 14:03:42 UTC

Problem appending rows to existing excel sheet

I am trying to appends new rows to an existing excel sheet. Although if I
open the file in a text editor I can see that the new rows have been
appended. Of course, I also see a lot of junk values which is fine. But the
moment I open the file using excel I see only the records added right after
the excel was created for the first time.

Here is my code,

	public static void writeExcel(String lOutputFileName, List aOutputLines)  {

		File lFile = new File(lOutputFileName);
		
		InputStream lFin = null;
		HSSFWorkbook lWorkBook = null;
		HSSFSheet lWorkSheet = null;
		FileOutputStream lFout = null;
		POIFSFileSystem lPOIfs = null;
		
		if (lFile.exists()) {
			
			try {
				lFout = new FileOutputStream(lOutputFileName, true);
				
				lFin = new FileInputStream(lOutputFileName);
				lPOIfs = new POIFSFileSystem(lFin);
				
				lWorkBook = new HSSFWorkbook(lPOIfs);
				lWorkSheet = lWorkBook.getSheet("DataSheet1");
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else {
			// Create new file
			try {
				lFout = new FileOutputStream(lOutputFileName);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			lWorkBook = new HSSFWorkbook();
			lWorkSheet = lWorkBook.createSheet("DataSheet1");
		}
		
		try {
			for (Iterator iter = aOutputLines.iterator(); iter.hasNext();) {

				Object lValue = iter.next();
				
				if (lValue == null) {
					System.out.println("=>NULL VALUE => " + lValue);
				}
				else {
					StringBuffer lSqlLine = (StringBuffer) lValue;
					
					HSSFRow lRow = lWorkSheet.createRow(lWorkSheet.getLastRowNum()+1);
					
					System.out.println("lWorkSheet.getLastRowNum() " +
lWorkSheet.getLastRowNum());
					
					HSSFCell lCell = lRow.createCell((short)0);
					
					lCell.setCellValue(lSqlLine.toString());
				}
			}
			lWorkBook.write(lFout);
			lFout.flush();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			try {
				lFout.close();
			}
			catch (IOException e) {
				e.printStackTrace();
			}			
		}
	}

-- 
View this message in context: http://www.nabble.com/Problem-appending-rows-to-existing-excel-sheet-tf3389342.html#a9434129
Sent from the POI - User mailing list archive at Nabble.com.


---------------------------------------------------------------------
To unsubscribe, e-mail: poi-user-unsubscribe@jakarta.apache.org
Mailing List:     http://jakarta.apache.org/site/mail2.html#poi
The Apache Jakarta Poi Project:  http://jakarta.apache.org/poi/