【发布时间】:2014-09-22 23:46:49
【问题描述】:
我正在尝试解决我遇到的 COMException 问题。这是我的代码:
错误发生在 Workbook Original = new Workbook(result[0]);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using MahApps.Metro;
using Microsoft.Win32;
using System.Windows.Forms;
using System.Data;
using Microsoft.Office.Interop.Excel;
namespace KPI_Generator_v3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
string [] result;
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
public MainWindow()
{
InitializeComponent();
}
private void exit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void browse_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
instructionslbl.Visibility = Visibility.Hidden;
dlg.Multiselect = true;
dlg.ShowDialog();
result = dlg.FileNames;
dlg.DefaultExt = ".xls";
dlg.Filter = "XLS Files (*.xls)|*.xls";
foreach (string fileName in result)
{
displayFilesBox.Text += fileName + System.Environment.NewLine;
}
SelectedFileslbl.Visibility = Visibility.Visible;
displayFilesBox.Visibility = Visibility.Visible;
generateBtn.Visibility = Visibility.Visible;
}
private void generate_Click(object sender, RoutedEventArgs e)
{
Workbook Original = new Workbook(result[0]);
for (int i = 1; i <= result.Length; i++)
{
Workbook next = new Workbook(result[i]);
Worksheet newOGsheet = Original.Worksheets.Add();
Worksheet nextSheet = next.Worksheets[0];
nextSheet.Copy(newOGsheet);
}
}
}
}
现在.. 虽然上面的代码可能无法正常工作,但我收到一个错误提示
“System.Runtime.InteropServices.COMException”发生在 mscorlib.dll 中
附加信息说明
HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
在谷歌上搜索了一段时间后,我下载了dependency walker,并得到以下输出:
我不知道我在做什么,我们将不胜感激!谢谢
编辑:HKEY CLASSES_ROOT 的 REGEDIT 图片(如果需要)
EDIT2:错误图片
【问题讨论】:
-
你在哪一行得到错误?从代码中我可以在这里看到一个错误
for (int i = 1; i <= result.Length; i++)。我认为需要将for (int i = 1; i < result.Length; i++)通知<=更改为<。您超过了结果数组 1。 -
错误在第 74 行 @ Workbook Original = new Workbook(result[0]);我相信我的系统没有正确注册的东西。当我尝试 regsvr32 Microsoft.Office.Interop.Excel.dll 时出现错误。另外,我在 HKEY CLASSES_ROOT 值处发布了一张 regedit 的图片
-
顺便说一下,当您使用 Office 互操作时,这些类型的异常似乎很常见。您可能想要切换到 Open Office XML SDK 或 EPPlus,因为它们完全在 .NET 框架中,并且不依赖 COM 与外部库进行通信。
-
您不能自己创建 WorkBook 对象,您必须使用工厂函数。请改用 Application.WorkBooks.Add()。顺便说一句,在 Office 对象模型中非常常见。有大量示例代码可帮助避免此类简单错误。
标签: c# excel comexception