![](/img/trans.png)
[英]Why does Microsoft.Office.Interop.Excel corrupts my excel file?
[英]Why does Microsoft.Office.Interop.Excel require a full path name to open a file?
我一直在嘗試在 Visual Studio 2012 中創建的 C# 應用程序中打開 Excel 文件。我終於發現我需要提供 ZC1D81AF5835844B4E9D936910DED8 的完整路徑名,盡管它與 FDCZZ 可執行文件存在於同一個文件夾中, . 這是為什么?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application ExcelApp = new Excel.Application();
try
{
MessageBox.Show("Current directory: " + Directory.GetCurrentDirectory());
if (File.Exists("PLC01.xls"))
{
MessageBox.Show("Target file exists.");
}
else
{
MessageBox.Show("Target file does not exist.");
}
Excel.Workbook workbook = ExcelApp.Workbooks.Open(Directory.GetCurrentDirectory() + "\\PLC01.xls");
// Excel.Workbook workbook = ExcelApp.Workbooks.Open("PLC01.xls");
workbook.Close();
MessageBox.Show("Book opened and closed.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
這個版本有效。 但是,如果我注釋掉對 Open() 的第一個調用並取消注釋第二個,它只給出文件名而不是完整路徑,我被告知找不到文件,即使“文件存在”消息框出現,驗證了它的存在。
Directory.GetCurrentDirectory
-
"獲取應用程序的當前工作目錄"
這里的“應用程序”是您的 C# 可執行文件:啟動的 Excel 應用程序實例未在與您的 C# 可執行文件相同的上下文中運行,因此它的“當前目錄”不一定相同。
如果您知道完整路徑,只需將其傳遞給 Excel - 無需嘗試僅傳遞文件名。
僅供參考 - GetCurrentDirectory
可能不是找到 Excel 文件的最可靠方法
似乎是 Microsoft 的某種“隱藏”實現, Workbooks.Open()
需要完整路徑。 老實說,這很奇怪,因為 VBA 中的這個很好用,而 Excel object 應該是一樣的(除非我沒記錯):
Sub TestMe()
Dim wb As Workbook
Set wb = Workbooks.Open("test.xlsx")
End Sub
對於.NetFramework,我嘗試在同一個文件夾中保存一個文件,其中Excel.exe
是:
C:\Program Files (x86)\Microsoft Office\Office14
我仍然收到找不到文件的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.