[英]How to upload Excel data into a SQL Server table with an auto incremented Id field using asp.net c# in a web forms application?
[英]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.