2

I exporting some data to existing excel file. Problem is that, user can have this file opened.

For reading and writing to excel I use Microsoft.Office.Interop.Excel.

Is possible edit file with showing changes in Excel desktop app? Or is possible to check if 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;

than I iterate over all sheets and fill data with writing values to Cells

Excel.Worksheet xlWorkSheet = worksheets.get_Item(sheetIndex);
Excel.Range range = GetRange(xlWorkSheet);

range.Cells[row,column] = value;

Then I save file:

xlWorkBook.Save();

Thank you Jakub

Jakub Čermoch
  • 431
  • 1
  • 9
  • 20
  • 2
    Not sure if that's what will help you, but you can check if [file is in use](http://stackoverflow.com/q/876473/1997232). – Sinatr Jan 05 '16 at 12:18
  • Can you show how do you try to open file? Your source code (VBA)? – Leo Chapiro Jan 05 '16 at 12:21
  • 1
    You can't edit and show changes while the file is in use unless it's a shared workbook. You can however check that the file is in use first but we would need to see your code to help further. – SierraOscar Jan 05 '16 at 12:21
  • I'd expand that as stated above, you can check if the book is locked / open and use shared workbooks. But if this is something you need to worry about user created workbooks or lots of users doing lots of strange stuff, you might be better creating SQL CE database or something similar and linking the Excel workbook to that for viewing / checking. – Austin T French Jan 05 '16 at 12:29

1 Answers1

3

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

Jakub Čermoch
  • 431
  • 1
  • 9
  • 20