none
DataGridView 数据导出到 Excel (VB) RRS feed

  • 问题

  • 我想要将DataGridView的数据导出到Excel,先描述一下要求和概况:

    使用语言:Visual Basic.NET

    数据库位置:(当前程序路径)\testdb.mdb

    数据库表名称:table_test

    数据库连接形式:OleDb

    列:col1、col2、col3

    导出到:D:\test.xlsx

    导出到样式:不需要过复杂导出样式,和数据库一样,有列标题和数据足矣

    Excel版本:Excel 2016,属于Office 365个人版

    VS版本:Visual Studio 2017 Community

    开发包版本:.NET Framework 4.6.1

    请问一下有没有人能够解决这个问题?将数据库数据导出到Excel?

    2018年8月27日 5:04

答案

  • 你好,

    可以考虑使用Interop.Excel 来做. 下面的代码你可以参考一下(导出部分代码):


    首先要添加引用:Microsoft.Office.Interop.Excel

    Dim MyExcel As New Microsoft.Office.Interop.Excel.Application()  
           MyExcel.Application.Workbooks.Add()  
           MyExcel.Visible = True  
      
           '获取标题  
           Dim Cols As Integer  
           For Cols = 1 To DataGridView1.Columns.Count  
               MyExcel.Cells(1, Cols) = DataGridView1.Columns(Cols - 1).HeaderText  
           Next  
      
           '往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  

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2018年8月27日 7:05
    版主