最近在做一个项目,目的是让用户将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 天来解决这个问题。如果您对我应该做什么有任何想法,我将非常感谢任何可以让我摆脱困境的建议!祝你今天过得愉快!:)
也许这会有所帮助:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句