Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening Excel sheet with full access in c#

Tags:

c#

.net

excel

I am writing an application that has to write a value to a cell in an excel spreadsheet. I am able to open the workbook, but it always opens in read-only mode. My code is

myExcelApp = new Excel.ApplicationClass();
myExcelApp.Visible = false;
Excel.Workbook myExcelWorkbooks = myExcelApp.Workbooks.Open(fileName, misValue, **false**, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);

Third argument is read-only which I have assigned as false. But still myExcelWorkbooks.readOnly shows only True.

Can someone help me out of this?

like image 816
Vasanth91 Avatar asked Dec 26 '22 11:12

Vasanth91


1 Answers

If you are on C# 4 or above, just do this:

var myExcelApp = new Excel.Application()
    {
        Visible=false
    };

Excel.Workbook myExcelWorkbooks = myExcelApp.Workbooks.Open(Filename: @"F:\oo\bar.xlsx", ReadOnly: false);

Once you are done, make sure you do this:

myExcelWorkbooks.Save();
myExcelWorkbooks.Close();

myExcelApp.Quit();

Marshal.ReleaseComObject(myExcelApp);

If you haven't been doing the second part, open task manager and kill every instance of EXCEL.EXE (or restart your machine), and try the first part again.

Excel will always open a workbook in read only mode if the Excel file is locked by another process. If you have been messing about with interop, and not killing the Excel process afterwards, this could explain the behavior you are seeing. Therefore your code and UAC settings may be fine, so I would get rid of any Excel instances running before changing your code further, or playing about with UAC.

like image 173
JMK Avatar answered Jan 13 '23 19:01

JMK