You guys may be able to tell me a better way to do this, but what I am wanting to do is I have a statement in my C# that creates a new instance of excel then codes...for example:
_Application docExcel = new Microsoft.Office.Interop.Excel.Application();
docExcel.Visible = true;
docExcel.DisplayAlerts = false;
_Workbook workbooksExcel = docExcel.ActiveWorkbook;
workbooksExcel = (_Workbook)(docExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet));
Worksheet worksheet = (Worksheet)docExcel.Worksheets["Sheet1"];
//more code down here to export datagrid to Excel
So with that being said, each time my function is called, I do not want it to run the above code, I only want it to run the above code if EXCEL IS NOT OPEN, OR this is the 1st time function is run. How can I do this in C#?
Loading
VulpesPosted Mar 13, 2013, 4:33 PM
private _Application docExcel;
private _Workbook workbooksExcel;
private Worksheet worksheet;
private void ExcelMethod()
{
if (docExcel == null)
{
docExcel = new Microsoft.Office.Interop.Excel.Application();
docExcel.Visible = true;
docExcel.DisplayAlerts = false;
workbooksExcel = (_Workbook)(docExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet));
worksheet = (Worksheet)docExcel.Worksheets["Sheet1"];
}
//more code down here to export datagrid to Excel
}
richard smithPosted Mar 15, 2013, 1:47 PM
VulpesPosted Mar 15, 2013, 1:06 PM
Worksheet sheetExcel = (Worksheet)(workbooksExcel.ActiveSheet;
then it must be because workBooksExcel hasn't been initialized at this point and so still has it's default value of null.
It might be best to disable buttons which assume that initialization has taken place until it has in fact been done.
richard smithPosted Mar 15, 2013, 11:52 AM
namespace Test
{
class Testing
{
private static _Application docExcel;
private static _Workbook workbooksExcel;
private static Worksheets worksheet;
public static void btn1_Click()
{
//Trouble line of code...
Worksheet sheetExcel = (Worksheet)(workbooksExcel.ActiveSheet;
((Range)sheetExcel.Cells["1", "A"]).Value2 = "Name";
}
And I get a debug error of NullReferenceException was unhandled.
brunda kPosted Mar 13, 2013, 11:38 PM
VulpesPosted Mar 13, 2013, 7:52 PM
Two possible ways to resolve it:
1. Change the name of the static field slightly to'workSheet. You'd then need to use this name throughout the method; or
2. When using 'worksheet' in the method always qualify it with the name of the enclosing class. So if, for example, the enclosing class is called Form1, then use Form1.worksheet within the method to distinguish it from the other 'worksheet'.
richard smithPosted Mar 13, 2013, 7:23 PM
//Decleration
VulpesPosted Mar 13, 2013, 4:54 PM
If it is, then make your fields static as well:
private static _Application docExcel;
private static _Workbook workbooksExcel;
private static Worksheet worksheet;
richard smithPosted Mar 13, 2013, 4:50 PM