C#: open read-only excel file

odoe

[H]F Junkie
Joined
Oct 10, 2001
Messages
9,796
I'm trying to work out a solution to open an Excel file on our network via C#. Eventually, I'll need to run a macro in the sheet, but I can't even get it open yet.

Here is what I have so far.

Code:
string path = @"\\testserver1\Data\Flow\Sigma\Sigma_doc.xls";
try
{
	Excel.Application excel = new Excel.Application();
	Excel.Workbook wb = excel.Workbooks.Open(path, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, true, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
        // the true values here have to do with opening in read-only mode, still fails
}
catch (Exception ex)
{
	System.Console.WriteLine("shoot me in the head");
	System.Console.WriteLine(ex.Message);
}
System.Console.ReadLine();

I get the following error.
"Attempted to read or write protected memory"

From what I can gather, this has to do with the excel file being read-only. Changing the permissions or getting the username/pass is not really an option at this time.
I can open the file by double-clicking it, no problem.

My goals here:
Open file as read-only.
(maybe need to add a sheet)
Launch macro that will read info from that sheet.
Let user close the file, no changes can be saved anyway.

Any nudge in a forward direction would be helpful, thanks.
If there is an easier way to do this in Python/Java or anything else I can run from a web service, I'm all ears.
 
I can open read-only excel files just fine when using the Excel COM.

Something along the lines of this should do (should be easy to translate to C#):
Code:
Dim xlsApp As Excel.Application = New Excel.Application
Dim xlsWorkbook As Excel.Workbook
Dim xlsWorksheet As Excel.Worksheet
Dim xlsCell As Excel.Range

xlsWorkbook = GetObject("C:\temp\temp.xlsm")
xlsWorksheet = xlsWorkbook.Worksheets("temp")
xlsCell = xlsWorksheet.Range("A1:B10")

'do work with cell range

xlsWorkbook.Close(SaveChanges:=False)
While System.Runtime.InteropServices.Marshal.ReleaseComObject(xlsWorkbook) > 0
End While

xlsApp.Workbooks.Close()
xlsApp.Quit()
 
Thanks, opening in COM got me halfway there. I can access the file data, but can't get it to appear in Excel. I'm trying to add the workbook object from COM to "Excel.Application excel"
excel.Workbooks is read-only.

I'll keep digging, thanks.
 
Ok, I think I got this.
I was originally using Microsoft.Office.Interop.Excel ref, but if I go with straight Excel COM ref, I can open the file just fine.

Thanks Snowknight26 for putting me in the COM direction.
 
Back
Top