代码之家  ›  专栏  ›  技术社区  ›  Vinoth

无法加载文件或程序集的Microsoft。办公室互操作。Excel,版本=14.0.0.0,区域性=中性,PublicKeyToken=71e9bce111e9429c’[重复]

  •  -3
  • Vinoth  · 技术社区  · 7 年前

    我有控制台应用程序。

    在这里,我想将数据集值导出到excel

    为此我要用这个 我用过微软。办公室互操作。擅长dll

    这是我的excel导出代码

     private static bool ExportDataTableToExcel(DataTable dt, string filepath)
        {
    
            Excel.Application oXL;
            Excel.Workbook oWB;
            Excel.Worksheet oSheet;
            Excel.Range oRange;
    
            try
            {      
                oXL = new Excel.Application();
                oXL.Visible = true;
                oXL.DisplayAlerts = false;
    
                oWB = oXL.Workbooks.Add(Missing.Value);
    
                oSheet = (Excel.Worksheet)oWB.ActiveSheet;
                oSheet.Name = "Data";
    
                int rowCount = 1;
                foreach (DataRow dr in dt.Rows)
                {
                    rowCount += 1;
                    for (int i = 1; i < dt.Columns.Count + 1; i++)
                    {
                        // Add the header the first time through 
                        if (rowCount == 2)
                        {
                            oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
                        }
                        oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
                    }
                }
    
    
                oRange = oSheet.get_Range(oSheet.Cells[1, 1],
                              oSheet.Cells[rowCount, dt.Columns.Count]);
                oRange.EntireColumn.AutoFit();
    
                oSheet = null;
                oRange = null;
                oWB.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookNormal,
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                    Excel.XlSaveAsAccessMode.xlExclusive,
                    Missing.Value, Missing.Value, Missing.Value,
                    Missing.Value, Missing.Value);
                oWB.Close(Missing.Value, Missing.Value, Missing.Value);
                oWB = null;
                oXL.Quit();
            }
            catch
            {
                throw;
            }
            finally
            {
    
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
    
            return true;
        }
    

    我的电脑中没有安装ms office。

    我以为我没有在电脑上安装MSOffice,所以只有我出错了。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Tom Schardt    7 年前

    Excel interop正在您的计算机上创建Excel实例-因此 您需要安装它才能使用它 . 此外,你必须有 Excel的正确版本