Greetings,
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
message:
"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;
try
{
GC.Collect(); // clean up any other excel guys hangin'
around...
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
["Connection"];
SqlConnection myConnection = new SqlConnection
(myConnString);
SqlCommand myCommand = new SqlCommand
(spName,myConnection);
myConnection.Open();
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
(k).ToString();
}
iRow++;
}// end while
myReader.Close();
myReader = null;
oSheet.get_Range("A1", "Z1").Font.Bold = true;
oSheet.get_Range("A1", "Z1").VerticalAlignment =
Excel.XlVAlign.xlVAlignCenter;
//AutoFit columns A:Z.
oRng = oSheet.get_Range("A1", "Z1");
oRng.EntireColumn.AutoFit();
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.
oWB.SaveAs
("C:\\Test.xls",Excel.XlFileFormat.xlWorkbookNorma l,null,null,false,fals
e,Excel.XlSaveAsAccessMode.xlShared,false,false,nu ll,null,null);
...
*** Sent via Developersdex http://www.developersdex.com ***