简体   繁体   中英

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):

在此处输入图片说明

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.

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.

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];

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