This project is read-only.

Open existing .xls and saving changes

Nov 17, 2009 at 2:14 PM

I'm opening an existing .xls file; Excel 2003, adding rows and populating columns. How do I save the changes?

      // copy the template file to a working file that will be populated
      File.Copy(templateFile, outputFile);

      // open the working file as a stream
      FileStream fs = new FileStream(outputFile, FileMode.Open, FileAccess.ReadWrite);

      // open the entire workbook
      HSSFWorkbook wb = new HSSFWorkbook(fs);

      // get reference to the "Project" worksheet
      HSSFSheet ws = wb.GetSheet("Project");

      // determine where the next row will be created
      nextRow = ws.LastRowNum + 1;

      // create the row
      HSSFRow row = ws.CreateRow(nextRow);

      // populate first two columns with some dummy data
      row.CreateCell(0).SetCellValue("Foo");
      row.CreateCell(1).SetCellValue("Bar");

      // save the changes
      wb.Write(fs); // error right here with a 'System.ObjectDisposedException' (cannot access a closed file)

      fs.Close();

Nov 17, 2009 at 4:31 PM
Edited Nov 20, 2009 at 3:11 PM

I must've been brain-dead... this works:

      // open the input file as a stream
      fs = new FileStream(inputFile, FileMode.Open, FileAccess.ReadWrite);

      // open the entire workbook
      HSSFWorkbook wb = new HSSFWorkbook(fs);

      fs.Close();

      // get reference to the "Project" worksheet
      HSSFSheet ws = wb.GetSheet("Project");

      // determine where the next row will be created
      nextRow = ws.LastRowNum + 1;

      // create the row
      HSSFRow row = ws.CreateRow(nextRow);

      // populate first two columns with some dummy data
      row.CreateCell(0).SetCellValue("Foo");
      row.CreateCell(1).SetCellValue("Bar");

      // create a filestream for the output file
      fs = new FileStream(outputFile, FileMode.Create);

      // save the changes
      wb.Write(fs);           

      fs.Close();