开发者

Opening Excel through C# then allowing the user to close Excel manually

After my program creates an Excel file, I let the user see that file.

Excel.Application xlApp = new Excel.Application();
xlApp.Visible开发者_运维技巧 = true;
Excel.Workbook excelWorkbook = xlApp.Workbooks.Open(xlsx.saveLocation + "\\" + xlsx.fileName,
    0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
    true, false, 0, true, false, false);

Whenever I close the Excel window, the process (EXCEL.EXE) remains (I'm hitting the red X in the top right). Am I missing a setting or something? I want the Excel window to be independent of the C# program, so that if I end the latter the former will still be visible.


If you want true independence, then you should use Process.Start to start Excel.

The simplest version you'd need would be:

Process.Start(Path.Combine(xlsx.saveLocation, xlsx.fileName));

though I'd recommend using the proper Path methods for combining the directory and filename into a complete path. Path.Combine

Source

If your path or filename has spaces then you need to wrap the whole thing in quotes:

var arguments = new StringBuilder("\"");
arguments.Append(Path.Combine(xlsx.saveLocation, xlsx.fileName));
arguments.Append("\"");
Process.Start(arguments.ToString());

(Though a StringBuilder may be overkill in this scenario)


You should open the file by calling Process.Start(filename).
This will open the file in the user's default program, without tying your code to Excel.

If you need to manipulate Excel, that won't help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜