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 CreateExcelWork book(string spName)
{
Excel.Applicati on oXL;
Excel._Workbook oWB;
Excel._Workshee t oSheet;
Excel.Range oRng;
try
{
GC.Collect(); // clean up any other excel guys hangin'
around...
oXL = new Excel.Applicati on();
oXL.Visible = true;
//Get a new workbook.
oWB = (Excel._Workboo k)(oXL.Workbook s.Add(
Missing.Value ));
oSheet = (Excel._Workshe et)oWB.ActiveSh eet;
//get our Data
string myConnString =
System.Configur ation.Configura tionSettings.Ap pSettings
["Connection "];
SqlConnection myConnection = new SqlConnection
(myConnString);
SqlCommand myCommand = new SqlCommand
(spName,myConne ction);
myConnection.Op en();
SqlDataReader myReader;
myReader = myCommand.Execu teReader();
// Create Header and sheet...
int iRow =2;
for(int j=0;j<myreader. fieldcount;j++)
{
oSheet.Cells[1, j+1] = myReader.GetNam e(j).ToString
();
}
// build the sheet contents
while (myReader.Read( ))
{
// Loop through each field.
for(int k=0;k < myReader.FieldC ount;k++)
{
oSheet.Cells[iRow,k+1]= myReader.GetVal ue
(k).ToString();
}
iRow++;
}// end while
myReader.Close( );
myReader = null;
oSheet.get_Rang e("A1", "Z1").Font. Bold = true;
oSheet.get_Rang e("A1", "Z1").VerticalA lignment =
Excel.XlVAlign. xlVAlignCenter;
//AutoFit columns A:Z.
oRng = oSheet.get_Rang e("A1", "Z1");
oRng.EntireColu mn.AutoFit();
oXL.Visible = true;
oXL.UserControl = true;
string strFile ="C:\report" +
System.DateTime .Now.Ticks.ToSt ring() +".xls";
Debug.WriteLine ("strFile : " + strFile);
// Code fails on next line.
oWB.SaveAs
("C:\\Test.xls" ,Excel.XlFileFo rmat.xlWorkbook Normal,null,nul l,false,fals
e,Excel.XlSaveA sAccessMode.xlS hared,false,fal se,null,null,nu ll);
...
*** Sent via Developersdex http://www.developersdex.com ***