Apparently Excel does not like you entering = as the first character in a cell. Replacing the first = with '= the problem is solved.
Exporting Datatable to Excel gives Exception from HRESULT: 0x800A03EC part way through
题
I'm trying to export a DataTable to Excel 2007. When I get to the Excel.Range line i partially exports the Array I created but then gives me an error (System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC). I'm able to see the Data in the Excel sheet and this error happens at Row 75 of the exported data. The value that it is dying on is ===> WATCH FOR CHANGES IN SEEPAGE - SUBSTANTIAL SEEPAGE OCCURS DOWNSTREAM OF THE EMBANKMENT, EAST SIDE OF DANIELS CREEK.
The value for the ExcelRange string is A1:CL1132.
Private Sub ExportExcelFast(ByVal dt As DataTable)
Try
Dim Excel As New Excel.Application
Dim Wb As Microsoft.Office.Interop.Excel.Workbook
Dim Ws As Microsoft.Office.Interop.Excel.Worksheet
Excel.SheetsInNewWorkbook = 1
Excel.Workbooks.Add()
Excel.Worksheets.Select()
Excel.Visible = True
Dim col, row As Integer
' Copy the DataTable to an object array
Dim rawData(dt.Rows.Count, dt.Columns.Count - 1) As Object
' Copy the column names to the first row of the object array
For col = 0 To dt.Columns.Count - 1
rawData(0, col) = dt.Columns(col).ColumnName.ToUpper
Next
' Copy the values to the object array
For col = 0 To dt.Columns.Count - 1
For row = 0 To dt.Rows.Count - 1
rawData(row + 1, col) = dt.Rows(row).ItemArray(col)
Next
Next
' Calculate the final column letter
Dim finalColLetter As String = String.Empty
finalColLetter = ExcelColName(dt.Columns.Count)
Dim excelRange As String = String.Format("A1:{0}{1}", _
finalColLetter, dt.Rows.Count + 1)
Excel.Range(excelRange, Type.Missing).Value2 = rawData
System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel)
Catch ex As Exception
Throw
End Try
End Sub
Public Function ExcelColName(ByVal Col As Integer) As String
If Col < 0 And Col > 256 Then
MsgBox("Invalid Argument", MsgBoxStyle.Critical)
Return Nothing
Exit Function
End If
Dim i As Int16
Dim r As Int16
Dim S As String
If Col <= 26 Then
S = Chr(Col + 64)
Else
r = CShort(Col Mod 26)
i = CShort(System.Math.Floor(Col / 26))
If r = 0 Then
r = 26
i = CShort(i - 1)
End If
S = Chr(i + 64) & Chr(r + 64)
End If
ExcelColName = S
End Function
解决方案
不隶属于 StackOverflow