Microsoft.Office.Interop.Excel为什么需要完整的路径名才能打开文件?

问题描述 投票:0回答:2

我一直试图在Visual Studio 2012中创建的C#应用​​程序中打开Excel文件的时间太长。我终于发现,我需要提供Excel文件的完整路径名,即使该文件名与可执行文件。为什么会这样?

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()的第一个调用,并取消注释第二个(仅提供文件名而不提供完整路径的)注释,那么我会被告知即使“文件存在”消息框也找不到该文件。出现,验证其存在。

c# .net excel office-interop
2个回答

-2
投票

[Microsoft似乎是某种“隐藏”的实现,Workbooks.Open()需要完整的路径。老实说,这很奇怪,因为VBA中的这个很好用,并且Excel对象应该是相同的(除非我没有记错):

© www.soinside.com 2019 - 2024. All rights reserved.