COMException C#Microsoft.Office.Interop.Excel
我想解决我遇到的一个COMException的问题。 这是我的代码:
工作簿原始=新工作簿(结果[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); } } } }
现在..虽然上面的代码可能无法正常工作我收到一个错误,说明
mscorlib.dll中发生“System.Runtime.InteropServices.COMException”
附加信息说
HRESULT:0x80040154(REGDB_E_CLASSNOTREG))
谷歌search了相当一段时间后,我已经下载依赖沃克,并有以下输出:
我不知道我在做什么,一些帮助将不胜感激! 谢谢
编辑:REGEDIT图片的HKEY_CLASSES_ROOT(如果需要)
编辑2:图片的错误
这个错误是不幸的COM互操作漏洞。 否则,你会得到一个编译错误,因为Workbook
是一个接口,并没有一个构造函数。 这个接口并不意味着被实例化,这就是为什么你得到这个exception。 (不知道为什么你在这里传递文件名…)
要解决此问题,请使用Microsoft.Office.Interop.Excel.Application:
using Microsoft.Office.Interop.Excel; Application excelApp = new Application(); excelApp.Workbooks.Open(result[0]);
其他说明:
- 你最后应该调用
dlg.ShowDialog()
– 这样,你的filter就会生效。 - 对于你的filter,我build议为.xlsx文件添加一个选项,以支持更新的Excel文件
- 添加
result.Length > 0
之前使用它,只是为了确保用户真正打开的东西。 - 改变你的循环条件为
i < result.Length
; 否则,你会得到一个IndexOutOfRangeException
另外,为了增加更多的信息,你可能会问:“但是等等,ryrich, Application
也是一个界面!我怎么能实例化它,而不是Workbook
?
我也想知道这一点。 显然这是有效的,因为它是用CoClassAttribute
(和一些其他属性)装饰的。 有关这方面的更多详细信息,请参阅此堆栈溢出文章。