DataGridView导出EXCEL

    ''' <summary> ''' 导出到Excel ''' </summary> ''' <param name="dgv">DataGridView</param> ''' <param name="NumberFormatColumnsIndex">数字转换为字符串的列序号</param> ''' <param name="ColumnsHeaderBold">列标题粗体</param> ''' <param name="ColumnWidthAutoFit">自动调整列宽(生成Excel速度减慢)</param> ''' <remarks>362*15 286,151(自动调整列宽 false),54(自动调整列宽,数字转换为字符串的列序号 false),53(false)</remarks> Public Sub ExportToExcel(ByVal dgv As System.Windows.Forms.DataGridView, Optional ByVal NumberFormatColumnsIndex As Integer() = Nothing, Optional ByVal ColumnsHeaderBold As Boolean = True, Optional ByVal ColumnWidthAutoFit As Boolean = False) Dim ea As New Excel.Application Dim ew As Excel.Workbook = ea.Workbooks.Add Dim es As Excel.Worksheet = ew.Sheets(1) ea.Visible = False For i As Integer = 0 To dgv.Columns.Count - 1 If dgv.Columns(i).Visible = True Then es.Cells(1, i + 1) = dgv.Columns(i).HeaderText es.Cells(1, i + 1).Font.Bold = ColumnsHeaderBold End If Next Dim lnCount As Integer lnCount = 0 For i As Integer = 0 To dgv.Rows.Count - 1 For j As Integer = 0 To dgv.Columns.Count - 1 If dgv.Columns(j).Visible = True Then If NumberFormatColumnsIndex IsNot Nothing Then For Each nfc As Integer In NumberFormatColumnsIndex If j = nfc Then es.Cells(i + 2, j + 1).NumberFormat = "@" Exit For End If Next End If Try es.Cells(i + 2, j + 1) = "'" & IIf(IsDBNull(dgv.Rows(i).Cells(j).Value), "", dgv.Rows(i).Cells(j).Value.ToString.Trim) Catch End Try If ColumnWidthAutoFit Then es.Cells(i + 2, j + 1).EntireColumn.AutoFit() End If End If Next Next ea.Visible = True System.Runtime.InteropServices.Marshal.ReleaseComObject(es) System.Runtime.InteropServices.Marshal.ReleaseComObject(ew) System.Runtime.InteropServices.Marshal.ReleaseComObject(ea) End Sub

 

记得添加Excel引用

你可能感兴趣的:(Excel,Integer,each)