从Excel导入时在Datagridview标题上获取F1(VB.Net)

时间:2016-01-19 20:11:42

标签: vb.net excel datagridview

我在项目中有2个按钮,可以从Excel导入并导出到Excel和datagridview。我可以毫无问题地导入Excel文件,但是当我从datagridview导出到Excel并尝试重新导入该文件时,我只得到一个列标题为" F1"在其中:

enter image description here

这是导出按钮的代码:

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    'Creamos las variables
    Dim exApp As New Excel.Application
    Dim exLibro As Excel.Workbook
    Dim exHoja As Excel.Worksheet

    Try
        'Añadimos el Libro al programa, y la hoja al libro
        exLibro = exApp.Workbooks.Add
        exHoja = exLibro.Worksheets.Add()
        ' ¿Cuantas columnas y cuantas filas?
        Dim NCol As Integer = DataGridView1.ColumnCount
        Dim NRow As Integer = DataGridView1.RowCount
        'Aqui recorremos todas las filas, y por cada fila todas las columnas

        'y vamos escribiendo.
        For i As Integer = 1 To NCol
            exHoja.Cells.Item(1, i) = DataGridView1.Columns(i - 1).Name.ToString
        Next
        For Fila As Integer = 0 To NRow - 1
            For Col As Integer = 0 To NCol - 1
                exHoja.Cells.Item(Fila + 2, Col + 1) = DataGridView1.Item(Col, Fila).Value
            Next
        Next
        'Titulo en negrita, Alineado al centro y que el tamaño de la columna
        'se ajuste al texto
        exHoja.Rows.Item(1).Font.Bold = 1
        exHoja.Rows.Item(1).HorizontalAlignment = 3
        exHoja.Columns.AutoFit()

        'Aplicación visible
        exApp.Application.Visible = True
        exHoja = Nothing
        exLibro = Nothing
        exApp = Nothing
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

我该怎么做才能解决它?

感谢。

2 个答案:

答案 0 :(得分:0)

从Excel导入,其中顶部图像描述使用SELECT *会发生什么 enter image description here

底部图像显示使用字段别名,如下面的代码所示

使用别名读取工作表数据的代码

Dim dt As New DataTable
Dim FileName As String = IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SampleData.xlsx")

Using cn As New OleDb.OleDbConnection With
    {
        .ConnectionString = ConnectionHelper.ConnectionString(FileName, "No")
    }
    Console.WriteLine(cn.ConnectionString)
    ' .CommandText = "SELECT F1 As FirstName, F2 As MiddleName, F3 As LastName FROM [PeopleData$] ORDER BY F3",

    Using cmd As New OleDb.OleDbCommand With
        {
            .CommandText = "SELECT F1 As FirstName, F2 As MiddleName, F3 As LastName FROM [Sheet1$] ORDER BY F3",
            .Connection = cn
        }
        cn.Open()
        dt.Load(cmd.ExecuteReader)
    End Using
End Using
DataGridView1.DataSource = dt

以上代码设置连接

Public Module ConnectionHelper
    Public Function ConnectionString(ByVal FileName As String) As String
        Dim Builder As New OleDb.OleDbConnectionStringBuilder
        If IO.Path.GetExtension(FileName).ToUpper = ".XLS" Then
            Builder.Provider = "Microsoft.Jet.OLEDB.4.0"
            Builder.Add("Extended Properties", "Excel 8.0;IMEX=2;HDR=No;")
        Else
            Builder.Provider = "Microsoft.ACE.OLEDB.12.0"
            Builder.Add("Extended Properties", "Excel 12.0;IMEX=2;HDR=No;")
        End If

        Builder.DataSource = FileName

        Return Builder.ConnectionString
    End Function
    Public Function ConnectionString(ByVal FileName As String, ByVal Header As String) As String
        Dim Builder As New OleDb.OleDbConnectionStringBuilder
        If IO.Path.GetExtension(FileName).ToUpper = ".XLS" Then
            Builder.Provider = "Microsoft.Jet.OLEDB.4.0"
            Builder.Add("Extended Properties", String.Format("Excel 8.0;IMEX=1;HDR={0};", Header))
        Else
            Builder.Provider = "Microsoft.ACE.OLEDB.12.0"
            Builder.Add("Extended Properties", String.Format("Excel 12.0;IMEX=1;HDR={0};", Header))
        End If

        Builder.DataSource = FileName

        Return Builder.ConnectionString
    End Function
End Module

请注意,工作表没有列名,ony数据。如果第一行具有列名,则连接将具有Yes作为参数2而不是如上所述.ConnectionString = ConnectionHelper.ConnectionString(FileName, "Yes")

enter image description here

答案 1 :(得分:0)

我找到了解决方案,问题不是导入按钮,而是它似乎是导出按钮,因为它导出文件带来某种损害。我尝试了我发现的其他代码(导出)并且工作,这是工作代码:

 Dim stRuta As String = ""
    Dim openFD As New OpenFileDialog()
    With openFD
        .Title = "Seleccionar archivos"
        .Filter = "Archivos Excel(*.xls;*.xlsx)|*.xls;*xlsx|Todos los archivos(*.*)|*.*"
        .Multiselect = False
        .InitialDirectory = My.Computer.FileSystem.SpecialDirectories.Desktop
        If .ShowDialog = Windows.Forms.DialogResult.OK Then
            stRuta = .FileName
        End If
    End With
    Try
        'Dim stConexion As String = ("Provider=Microsoft.ACE.OLEDB.12.0­;" & ("Data Source=" & (stRuta & ";Extended Properties=""Excel 12.0;Xml;HDR=YES;IMEX=2"";")))
        Dim stConexion As String = ("Provider=Microsoft.ACE.OLEDB.12.0;" & ("Data Source=" & (stRuta & ";Extended Properties=""Excel 12.0;Xml;HDR=YES;IMEX=2"";")))
        Dim cnConex As New OleDbConnection(stConexion)
        Dim Cmd As New OleDbCommand("Select * From [Hoja1$]")
        Dim Ds As New DataSet
        Dim Da As New OleDbDataAdapter
        Dim Dt As New DataTable
        cnConex.Open()
        Cmd.Connection = cnConex
        Da.SelectCommand = Cmd
        Da.Fill(Ds)
        Dt = Ds.Tables(0)
        Me.DataGridView1.Columns.Clear()
        Me.DataGridView1.DataSource = Dt
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
    End Try

谢谢大家:)