Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open workbook by filename without displaying Excel window?

I get currentWrkBook by fileName with the code below:

using Excel = Microsoft.Office.Interop.Excel;
...
Excel.Workbook currentWrkBook = Excel.Application.Workbooks.Open(fileName);
...

Result get OK (when run to the statement above, the fileName[D:/DataProject/Resources.xlsm] is open):

enter image description here

Now, I would like get currentWrkBook by fileName without open file.

That is possible? Any tips on these will be great help. Thanks in advance.

like image 892
MinhKiyo Avatar asked Oct 28 '25 10:10

MinhKiyo


2 Answers

Try to open your file from new Application object:

var excel = new Excel.Application();
var workbook = excel.Workbooks.Open(filename);

It is possible, that you have excel instance already running, then new workbook becomes visible as well.

EDIT: In case if you need to get a reference for a workbook that is already opened you can get it by name:

Excel.Workbook currentWrkBook = Excel.Application.Workbooks[fileName];
like image 75
default locale Avatar answered Oct 30 '25 00:10

default locale


I seem to be able to do this by opening the file in read-only mode. For me, that's good enough as I just need to read the data.

var oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = false;

Workbook Wbook = oXL.Workbooks.Open(txtFileName.Text, ReadOnly: true, Password: "password");

var sheet = Wbook.Worksheets[1];

foreach (Range row in sheet.UsedRange.Rows)
{
    var firstName = sheet.Cells[row.Row, 1].Value2,
    var lastName = sheet.Cells[row.Row, 2].Value2
}

If I switch the ReadOnly parameter to false, then Excel will open the file visibly.

like image 26
Trent Avatar answered Oct 30 '25 00:10

Trent