We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Exporting chart to open Excel Workbook

Hi,

I want to add a worksheet/chartsheet to a workbook which is already open and active. I try to do this using (C#):

ExcelEngine excelEngine = new ExcelEngine();
IWorksheet sheet = excelEngine.Excel.ActiveWorkbook.Worksheets.Create();

but ActiveWorkbook is always null so I get an exception. How can I access the open/active workbook? I saw a similar post below where you suggest

IWorksheet sheet = application.ActiveWorkbook.Worksheets.Create();

But application always refers to a System object when I try this. Any solutions?

Thanks




3 Replies

GM Geetha M Syncfusion Team June 3, 2010 04:44 AM UTC

Hi,

Thank you for your interest in Syncfusion products.

The code snippet you have used does not have any workbook initialized and thus causes exception. If you are to create a new workbook, you can make use of the following code.

ExcelEngine excelEngine = new ExcelEngine();
IWorkbook workbook = excelEngine.Excel.Workbooks.Create(1);
IWorksheet sheet = workbook.Worksheets[0];

// user code goes here

IWorksheet newSheet = excelEngine.Excel.ActiveWorkbook.Worksheets.Create();

Please try this and let me know if you have any questions.

Regards,
Geetha


FS Farman Samee June 3, 2010 09:55 AM UTC

Ok thanks- does this mean that I can't access the workbook which is currently active in Excel, unless I have just created it myself using the Excel Engine object? I don't want to create the (currently open) workbook myself, the user will have opened this manually. I just want to access it, in order to add some sheets. Can I do this? (ps. please bear in mind I can't seem to access the Excel 'Application' object, if I need to do this can you let me know the full namespace).
Thanks



GM Geetha M Syncfusion Team June 4, 2010 12:18 PM UTC

Hi,

Thank you for the details.

I was able to reproduce the NullReference exception when accessing ActiveWorkbook after loading a workbook. Could you please workaround this using the following code snippet?

ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
IWorkbook workbook = application.Workbooks.Open(@"..\..\Input.xlsx", ExcelOpenType.Automatic);

IWorkbook book = application.ActiveSheet.Workbook;

IWorksheet sheet = book.Worksheets.Create("New");

workbook.SaveAs("Sample.xlsx");
workbook.Close();
excelEngine.Dispose();

The workaround is to load the Workbook of the ActiveSheet.

Also, IApplication interface can be accessed using Syncfusion.XlsIO namespace.

Please try this and let me know if you have any questions.

Regards,
Geetha

Loader.
Live Chat Icon For mobile
Up arrow icon