By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,417 Members | 1,845 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,417 IT Pros & Developers. It's quick & easy.

"Workbook.SaveAs" Failing

P: n/a

I have the code below where I am instantiating Excel and then attempting
to the save the new workbook (as "Test.xls"). However, on the line of
code that attempts to save the workbook, I receive the following error

"Object reference not set to an instance of an object."

Any ideas as to what I am doing wrong? [Note: oWB.Save() works fine,
just not oWB.SaveAs()].

Thanks in advance!

************************************************** ********

public static void CreateExcelWorkbook(string spName)
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
GC.Collect(); // clean up any other excel guys hangin'
oXL = new Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add(
Missing.Value ));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
//get our Data
string myConnString =
System.Configuration.ConfigurationSettings.AppSett ings
SqlConnection myConnection = new SqlConnection
SqlCommand myCommand = new SqlCommand
SqlDataReader myReader;
myReader = myCommand.ExecuteReader();
// Create Header and sheet...
int iRow =2;
for(int j=0;j<myreader.fieldcount;j++)
oSheet.Cells[1, j+1] = myReader.GetName(j).ToString
// build the sheet contents
while (myReader.Read())
// Loop through each field.
for(int k=0;k < myReader.FieldCount;k++)
oSheet.Cells[iRow,k+1]= myReader.GetValue
}// end while
myReader = null;
oSheet.get_Range("A1", "Z1").Font.Bold = true;
oSheet.get_Range("A1", "Z1").VerticalAlignment =
//AutoFit columns A:Z.
oRng = oSheet.get_Range("A1", "Z1");
oXL.Visible = true;
oXL.UserControl = true;
string strFile ="C:\report" +
System.DateTime.Now.Ticks.ToString() +".xls";
Debug.WriteLine("strFile : " + strFile);
// Code fails on next line.
("C:\\Test.xls",Excel.XlFileFormat.xlWorkbookNorma l,null,null,false,fals
e,Excel.XlSaveAsAccessMode.xlShared,false,false,nu ll,null,null);

*** Sent via Developersdex ***
May 3 '06 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.