Reputation: 471
I am exporting some data to an existing Excel file. The problem is that the user may have this file opened.
For reading and writing to excel I use Microsoft.Office.Interop.Excel.
Is it possible to edit the file and show changes in the Excel desktop app? Or is it possible to check if the file is opened in Excel?
This is how I open that file:
xlApp = new Excel.Application();
xlApp.DisplayAlerts = false;
workbook = xlApp.Workbooks;
xlWorkBook = workbook.Open(filePath, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", true, false, 0, true, false, false);
var worksheets = xlWorkBook.Worksheets;
Then I iterate over all sheets and fill in data by writing values to cells:
Excel.Worksheet xlWorkSheet = worksheets.get_Item(sheetIndex);
Excel.Range range = GetRange(xlWorkSheet);
range.Cells[row,column] = value;
Then I save the file:
xlWorkBook.Save();
Thank you Jakub
Upvotes: 2
Views: 3135
Reputation: 471
Whole magic is:
try
{
xlApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
}
catch (Exception ex)
{
if (ex.ToString().Contains("0x800401E3 (MK_E_UNAVAILABLE)"))
{
xlApp = new Excel.Application();
}
else
{
throw;
}
}
this will get opened excel application. Then all changes are made in this instance of Excel. So everything is edited, is seen in opened excel application.
thanks guys
Upvotes: 5