繁体   English   中英

使用文件上传将Excel数据传输到SQL Server表中

[英]Transfer Excel data into a SQL Server table using file upload

我需要为用户提供文件上传功能,用户可以在其中浏览文件并将其上传到服务器。 存储在文件中的数据将被提取并插入表中。

前端代码:

<asp:Panel ID="panelFileUpload" runat="server">
    <table>
        <tr>
            <td><asp:Label ID="lblFileUpload" runat="server" Text="File Upload:"></asp:Label></td>
            <td><asp:FileUpload CssClass = "FileUpload" ID="fuFileUpload" runat="server" />
                <asp:Button ID="btnUploadFile" runat="server" CssClass="inputButton" OnClientClick="fnStartInterval()" Text="Upload" ValidationGroup="A" />
                <asp:RequiredFieldValidator ID="RFValidator" runat="server" ControlToValidate="fuFileUpload" Font-Italic="True" Display="Dynamic" ValidationGroup="A">*Please choose a file to upload! </asp:RequiredFieldValidator>
            </td>
        </tr>
    </table>
</asp:Panel>

我找到了用于文件上传的后端代码,但这不起作用。 我的Excel文件有4个cols-col1 ... col4。 我不确定如何将Excel的列映射到表结构。

后端代码:

Protected Sub btnUploadFile_Click(sender As Object, e As EventArgs) Handles btnUploadFile.Click
    Dim filename As String = Path.GetFileName(fuFileUpload.PostedFile.FileName)
    Dim contentType As String = fuFileUpload.PostedFile.ContentType
    Using fs As Stream = fuFileUpload.PostedFile.InputStream
        Using br As New BinaryReader(fs)
            Dim bytes As Byte() = br.ReadBytes(CType(fs.Length, Integer))
            Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using con As New SqlConnection(constr)
                Dim query As String = "INSERT INTO dbo..table_1 VALUES (@ContentType, @Data)"
                Using cmd As New SqlCommand(query)
                    cmd.Connection = con
                    cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value = contentType
                    cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes
                    con.Open()
                    cmd.ExecuteNonQuery()
                    con.Close()
                End Using
            End Using
        End Using
    End Using

End Sub 

在这里,contenttype是直接从文件读取的。 有没有一种方法可以按原样读取所有4列并将其存储在表中。

对此没有任何保证,但是它应该使您知道如何实现。

DataTable的来源不可知,因此您可以对从Excel检索的数据和从Sql Server插入的数据使用相同的DataTable。

Private Sub UpdateSQLServerFromExcel(FilePath As String)
    Dim dt = New DataTable()

    Using cnSource As New OleDbConnection($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={FilePath};Extended Properties=""Excel 12.0 Xml;HDR=YES"";")
        Using selectCommand As New OleDbCommand("Select * From [Sheet1$];", cnSource)
            Using da As New OleDbDataAdapter
                'The following allows the .DataRowState to remain as Added (normally it is changed to Unchanged by the .Fill method)
                da.AcceptChangesDuringFill = False
                da.Fill(dt)
            End Using
        End Using
    End Using

    Using cnDestination As New SqlConnection("Your Sql Server connection string")
        Using selectCommand As New SqlCommand("Select * From YourSqlTableName;", cnDestination)
            Using da As New SqlDataAdapter()
                da.SelectCommand = selectCommand
                Dim cb As New SqlCommandBuilder(da)
                da.Update(dt)
            End Using
        End Using
    End Using
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM