从datagridview中导出Excel

在导出之前要先进行一些设置:

将datagridview的allowUsersToAddRows属性设置为false

添加引用      项目——添加引用——.net——Microsoft .Office.Interop.Excel

 

导出Excel:

      '要先添加引用才能用到 Microsoft.Office.Interop.Excel.Application()
        Dim MyExcel As New Microsoft.Office.Interop.Excel.Application()
        MyExcel.Application.Workbooks.Add(True)
        MyExcel.Visible = True

        '将datagridview中的字段名导出
        Dim m As Integer
        For m = 0 To DataGridView1.ColumnCount - 1
               MyExcel.Cells(1, m + 1) = Me.DataGridView1.Columns(m).HeaderText
        Next m

        '往excel表里添加数据
        Dim i As Integer
        For i = 0 To DataGridView1.RowCount - 1
              Dim j As Integer
              For j = 0 To DataGridView1.ColumnCount - 1
                    If Me.DataGridView1(j, i).Value Is System.DBNull.Value Then

                           MyExcel.Cells(i + 2, j + 1) = ""
                    Else
                           MyExcel.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString

                    End If
              Next j
        Next i


你可能感兴趣的:(.net,Excel,Microsoft,Integer)