简体   繁体   中英

Opening Excel sheet with full access in c#

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?

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.

UAC may be interfering with it somehow. Try launching either your app or Visual Studio as an administrator (from the context menu)

Try use OpenXml, on codeplex there are a wrapper for simply iteracion.

http://closedxml.codeplex.com/

 xl = new Excel.Application();
 Excel.Workbooks books = xl.Workbooks;
 Excel.Workbook book = books.Open(filepath);

This always works for me, and it will be invisible by default and opened for read/write. You should use Excel.Application() rather than Excel.ApplicationClass() apparently but I doubt that is the route of your problem (I also can't find the article where I read that I'm afraid). Also notice how I split declaring the Workbooks and the Workbook object, again apparently that is best practice otherwise the process you launch won't always get closed.

I did a large project using Interop.excel. The pitfalls are horrible and when you start doing more advanced functions or processing large data sets it is extremely slow.

Try out OpenXML/ClosedXML, this will make your life a lot easier and your program architecture more scalable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM