1

我目前有我的 datagridview 从 mysql 表中导入数据。导入信息后(通常为 1000 行 x 15 列),用户可以将数据导出到 Excel。然后,用户必须运行一个宏以根据第 1 列中的内容将数据分成单独的工作表(根据值将相同的行组合在一起),然后运行另一个宏以将每个单独的工作表保存到文件夹中它自己的电子邮件文件中. 第 1 列的内容可以具有保存值 - 例如

在此处输入图像描述

一旦用户单击按钮,是否有可能让 vb.net 在以下步骤中自动执行此功能:

  1. 按第 1 列中的内容对 dgv 进行排序,
  2. 开始根据第 1 列中的内容将数据保存到指定文件夹中的单独文件中(所有 jim 和 bill 都在特定文件夹中)
  3. 文件名将是第 1 列中内容的名称。
  4. 完成后会弹出一个窗口,表明项目已保存。

我用于 dgv 导出的当前代码。

  'export to excel
    'verfying the datagridview having data or not
    If ((DataGridView1.Columns.Count = 0) Or (DataGridView1.Rows.Count = 0)) Then
        Exit Sub
    End If

    'Creating dataset to export
    Dim dset As New DataSet
    'add table to dataset
    dset.Tables.Add()
    'add column to that table
    For i As Integer = 0 To DataGridView1.ColumnCount - 1
        dset.Tables(0).Columns.Add(DataGridView1.Columns(i).HeaderText)
    Next
    'add rows to the table
    Dim dr1 As DataRow
    For i As Integer = 0 To DataGridView1.RowCount - 1
        dr1 = dset.Tables(0).NewRow
        For j As Integer = 0 To DataGridView1.Columns.Count - 1
            dr1(j) = DataGridView1.Rows(i).Cells(j).Value
        Next
        dset.Tables(0).Rows.Add(dr1)
    Next

    Dim excel As New Microsoft.Office.Interop.Excel.Application
    Dim wBook As Microsoft.Office.Interop.Excel.Workbook
    Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet

    wBook = excel.Workbooks.Add()
    wSheet = wBook.ActiveSheet()

    Dim dt As System.Data.DataTable = dset.Tables(0)
    Dim dc As System.Data.DataColumn
    Dim dr As System.Data.DataRow
    Dim colIndex As Integer = 0
    Dim rowIndex As Integer = 0

    For Each dc In dt.Columns
        colIndex = colIndex + 1
        excel.Cells(1, colIndex) = dc.ColumnName
    Next

    For Each dr In dt.Rows
        rowIndex = rowIndex + 1
        colIndex = 0
        For Each dc In dt.Columns
            colIndex = colIndex + 1
            excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)

        Next
    Next

    wSheet.Columns.AutoFit()
    Dim strFileName As String = "C:\exports\jim.xls"
    Dim blnFileOpen As Boolean = False
    Try
        Dim fileTemp As System.IO.FileStream = System.IO.File.OpenWrite(strFileName)
        fileTemp.Close()
    Catch ex As Exception
        blnFileOpen = False
    End Try

    If System.IO.File.Exists(strFileName) Then
        System.IO.File.Delete(strFileName)
    End If

    wBook.SaveAs(strFileName)
    excel.Workbooks.Open(strFileName)
    excel.Visible = True
4

0 回答 0