我在ASP.NET中创建了一个程序,使用ASP.NET将Excel中的值导入SQL Server数据库表。问题是,每当我尝试更新Excel文件列中的值并尝试再次导入文件以更新SQL Server表时,列而不是替换同一列的现有文件,它会再次被复制,因此具有修改值的整个数据值最终会出现在新行中。
我上传文件的html代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Import" OnClick="btnUpload_Click" />
<br />
<br />
</div>
</form>
</body>
</html>
我的ASP.NET代码,用于将数据从excel导入到SQL Server数据库:
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
public partial class Default2 : System.Web.UI.Page
{
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string sPath = Server.MapPath("~/BulkFolder/" + FileUpload1.FileName);
FileUpload1.SaveAs(sPath);
ImporttoSQL(sPath);
}
}
private void ImporttoSQL(string sPath)
{
string sSourceConstr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", sPath);
string sDestConstr = ConfigurationManager.ConnectionStrings["masterConnectionString1"].ConnectionString;
OleDbConnection sSourceConnection = new OleDbConnection(sSourceConstr);
using (sSourceConnection)
{
string sql = string.Format("select [Employee Name],[Designation],[Posting],[Dept] FROM [{0}]", "Sheet1$");
OleDbCommand command = new OleDbCommand(sql, sSourceConnection);
sSourceConnection.Open();
using (OleDbDataReader dr = command.ExecuteReader())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sDestConstr))
{
bulkCopy.DestinationTableName = "Employee";
bulkCopy.WriteToServer(dr);
}
}
}
}
}
在SQL Server中创建表的代码:
CREATE TABLE [dbo].[Employee]
(
[Employee Name] [varchar](max) NOT NULL,
[Designation] [varchar](max) NOT NULL,
[Posting] [varchar](max) NOT NULL,
[Dept] [varchar](max) NOT NULL
)
看一下Excel文件:
My Excel file columns and their values
我用“saurabh sharma”替换了员工姓名 - “Robert Vodro”
但是,不是替换数据库中的值,而是通过修改再次复制了整个表值。请帮帮我...
如果可能的话,我可以在我的代码中实现哪些方法清除存储在SQL Server表中的所有旧值,并在运行代码时将其替换为新值?