使用 C# Microsoft.Office.Interop.Excel 但出现错误无法加载文件 Version=15.0.0.0

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

尝试将数据从 Excel 工作表导入到 Sql Server 表中。该代码由用户窗体中的按钮激活。但当我点击它时,出现以下错误。我使用的是工作机器,我们有 Microsoft Excel 365。我已经读到这可能是一个问题,但下面是否说它找不到互操作文件?我已经阅读了周围的内容,但无法确定哪些答案与我的具体问题相关。

System.IO.FileNotFoundException:无法加载文件或程序集“office,Version=15.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c”。该系统找不到指定的文件。 文件名:'office,版本=15.0.0.0,文化=中性,PublicKeyToken=71e9bce111e9429c'

using Microsoft.Office.Interop.Excel;

namespace FormSqlInsertCsv
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel.Application xlApp;
            Microsoft.Office.Interop.Excel.Workbook xlWorkbook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorksheet;
            Microsoft.Office.Interop.Excel.Range xlRange;

            int xlRow;
            string strFileName;

            openFD.Filter = "Excel Office |*.xls; *xlsx";
            openFD.ShowDialog();
            strFileName = openFD.FileName;

            if(strFileName != "")
            {
                xlApp = new Microsoft.Office.Interop.Excel.Application();
                xlWorkbook = xlApp.Workbooks.Open(strFileName);
                xlWorksheet = (Worksheet)xlWorkbook.Worksheets["Sheet1"];
                //xlRange = xlWorksheet.UsedRange;
                xlRange = (Microsoft.Office.Interop.Excel.Range)xlWorksheet.UsedRange;

                int i = 0;

                for(xlRow = 2; xlRow <= xlRange.Rows.Count; xlRow++)
                {
                    i++;
                    dgvEmployees.Rows.Add(i, xlRange.Cells[xlRow, 1].ToString(), xlRange.Cells[xlRow, 2].ToString(), xlRange.Cells[xlRow, 3].ToString(), xlRange.Cells[xlRow, 4].ToString(), xlRange.Cells[xlRow, 5].ToString(), xlRange.Cells[xlRow, 6].ToString());

                }
                xlWorkbook.Close();
                xlApp.Quit();
            }
        }
    }
}
c# excel office365 office-interop office-automation
2个回答
1
投票

右键单击引用并从以下位置添加 Office.dll 引用 C/Windows/ assembly/GAC_MSIL/office/15.0.0.0__71e9bce111e9429c/Office.dll


0
投票

右键单击引用并从以下位置添加 Office.dll 引用 C/Windows/ assembly/GAC_MSIL/office/15.0.0.0__71e9bce111e9429c/Office.dll

对我来说非常有效!

非常感谢。

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