如何将datagridview的确切值导出到excel VB中

时间:2015-02-04 03:02:40

标签: vb.net excel datagridview

我有一个datagridview,其中填充了导入的excel文件中的值。我将datagridview中的headertext更改为另一个值并重新排序,然后再将它们导出到excel文件中。发生了什么是我获得了更改但不是订单的值(订单仍然是导入的Excel文件的顺序)。如何导入datagridview的值和顺序?请参阅以下代码:

'Code for Import
Private Sub btnImport_Click(sender As System.Object, e As System.EventArgs) Handles btnImport.Click
    Dim result As DialogResult = OpenFileDialog1.ShowDialog()
    Dim path As String = OpenFileDialog1.FileName
    Me.TextBox1.Text = path.ToString

    Try
        Me.dgvFile.DataSource = Nothing
        Dim MyConnection As System.Data.OleDb.OleDbConnection
        Dim DtSet As System.Data.DataSet
        Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
        MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & Me.TextBox1.Text & "';Extended Properties=Excel 8.0;")
        MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
        MyCommand.TableMappings.Add("Table", "Net-informations.com")
        DtSet = New System.Data.DataSet
        MyCommand.Fill(DtSet)
        Me.dgvFile.DataSource = DtSet.Tables(0)

        MyConnection.Close()

        MessageBox.Show("File successfully imported")

    Catch ex As Exception
        MessageBox.Show("Error")
    End Try
End Sub

'Code for Convert
Private Sub btnConvert_Click(sender As System.Object, e As System.EventArgs) Handles btnConvert.Click

    MysqlConn = New MySqlConnection
    MysqlConn.ConnectionString = "server=localhost;userid=root;password=NewPass;database=converter"
    Dim MysqlReader As MySqlDataReader

    'Convert for Headers
    MysqlConn.Open()
    Dim MysqlQuery As String
    MysqlQuery = "SELECT * FROM headers"
    MysqlComm = New MySqlCommand(MysqlQuery, MysqlConn)
    MysqlReader = MysqlComm.ExecuteReader

    Dim y = 0
    Dim arrayContain As New List(Of String)
    Dim arrayRemove As New List(Of String)
    'Dim colIndex

    While MysqlReader.Read
        Dim header = MysqlReader.GetString("Header")
        Dim convert = MysqlReader.GetString("Convert")
        Dim strHeader = System.Convert.ToString(header)
        Dim strConvert = System.Convert.ToString(convert)
        Dim x = 0

        For Each column As DataGridViewColumn In dgvFile.Columns
            If column.HeaderText = strHeader Then
                column.HeaderText = strConvert
                dgvFile.Columns(x).DisplayIndex = y
                y = y + 1
                arrayContain.Add(column.HeaderText)
            Else
                x = x + 1
            End If
        Next
    End While

    For Each remove As DataGridViewColumn In dgvFile.Columns
        If arrayContain.Contains(remove.HeaderText) = False Then
            arrayRemove.Add(remove.HeaderText)
        End If
    Next

    For count As Integer = 0 To arrayRemove.Count - 1
        dgvFile.Columns.Remove(arrayRemove(count))
    Next

    MysqlComm.Dispose()
    MysqlReader.Close()
    MysqlConn.Close()

'Code for Export
Private Sub btnExport_Click(sender As System.Object, e As System.EventArgs) Handles btnExport.Click
    Dim xlApp As Microsoft.Office.Interop.Excel.Application
    Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
    Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
    Dim misValue As Object = System.Reflection.Missing.Value
    Dim sPath As String = String.Empty
    Dim dlgSave As New SaveFileDialog
    Dim i As Integer
    Dim j As Integer

    dlgSave.DefaultExt = "xlsx"
    dlgSave.Filter = "Microsoft Excel|*.xlsx"

    If dlgSave.ShowDialog = System.Windows.Forms.DialogResult.OK Then
        xlApp = New Microsoft.Office.Interop.Excel.Application
        xlWorkBook = xlApp.Workbooks.Add(misValue)
        xlWorkSheet = xlWorkBook.Sheets("sheet1")


        For i = 0 To dgvFile.RowCount - 1
            For j = 0 To dgvFile.ColumnCount - 1
                For k As Integer = 1 To dgvFile.Columns.Count
                    xlWorkSheet.Cells(1, k) = dgvFile.Columns(k - 1).HeaderText
                    xlWorkSheet.Cells(i + 2, j + 1) = "'" & dgvFile(j, i).Value.ToString()
                Next
            Next
        Next

        Dim sFileName As String = dlgSave.FileName
        'Dim finalFilename As String = sFileName & ".xlsx"
        xlWorkSheet.SaveAs(sFileName)
        xlWorkBook.Close()
        xlApp.Quit()

        releaseObject(xlApp)
        releaseObject(xlWorkBook)
        releaseObject(xlWorkSheet)

        Dim res As MsgBoxResult
        res = MsgBox("Process completed, Would you like to open file?", MsgBoxStyle.YesNo)
        If (res = MsgBoxResult.Yes) Then
            Process.Start(sFileName)
        End If
    End If

End Sub

'releaseObject Code
Private Sub releaseObject(ByVal obj As Object)
    Try
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
        obj = Nothing
    Catch ex As Exception
        obj = Nothing
    Finally
        GC.Collect()
    End Try
End Sub

修改

这是IMPORTED excel到datagridview的顺序。 columns1 这是CONVERTED datagridview的顺序。 columns2 这是EXPORTED datagridview excel的顺序。 columns3

您会注意到IMPORTED和EXPORTED具有相同的订单。我希望EXPORTED与CONVERTED的顺序相同。我希望现在很清楚,我希望有人可以帮我解决这个问题。谢谢:))

1 个答案:

答案 0 :(得分:1)

尝试使用转换期间所需的值更改dt中的值,而不是更改datagridview,并使用转换后的值将dtv数据源作为dt。我认为导出获取dt内的值而不是datagridview。