最近我一直致力于一个项目,旨在允许用户将DataGridView中完成的数据作为Excel表发送,首先必须将表保存在用户的PC中。我正在使用下面显示的代码:
Private Sub Bt2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt2.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Int16, j As Int16
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To dg.RowCount - 2
For j = 0 To dg.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = dg(j, i).Value.ToString()
Next
Next
xlWorkBook.SaveAs("C:\Users\Abstract\Desktop\file1.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue)
xlWorkBook.Close(True, misValue, misValue)
xlApp.Quit()
releaseObject(xlWorkSheet)
releaseObject(xlWorkBook)
releaseObject(xlApp)
MessageBox.Show("Over")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
MessageBox.Show("Exception Occured while releasing object " + ex.ToString())
Finally
GC.Collect()
End Try
End Sub
用户单击该按钮将其DataGrid另存为Excel表格。但是,执行此操作后,我得到一个异常(在第一行,我将xlApp设置为Excel应用程序),并带有以下文本:
COM Exception Ocurred
Exception thrown: 'System.Runtime.InteropServices.COMException' in trimitere_excel.exe
Additional information: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
我一直在寻找将近2天才能克服这个问题。如果您对我应该做的事情有任何了解,我会非常感激任何可以让我摆脱困境的建议! 祝你今天愉快! :)
答案 0 :(得分:0)
也许这会有所帮助:
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports Microsoft.Office.Interop
Private Sub Bt2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt2.Click
Dim pathExcel As String = "C:\Users\Abstract\Desktop\file1.xls"
Dim xlApp As Excel.Application = New Excel.Application
Dim misValue As Object = System.Reflection.Missing.Value
Dim xlWorkBook As Excel.Workbook
xlWorkBook = xlApp.Workbooks.Add(misValue)
Dim xlWorksheet As Excel.Worksheet = xlWorkBook.Sheets("sheet1")
For i = 0 To dg.RowCount - 2
For j = 0 To dg.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = dg(j, i).Value.ToString()
Next
Next
xlWorkBookSum.SaveAs(pathExcel)
xlWorkBookSum.Close()
xlApp.Quit()
releaseObject(xlWorkSheet)
releaseObject(xlWorkBook)
releaseObject(xlApp)
MessageBox.Show("Over")
End Sub