C# 如何将excel工作表中的数据导入sql server表?
嗨。我想将excel工作表数据导入SQL server表,为此我编写了如下代码。工作表正在上传到文件夹中,但数据没有导入到表中,有人能告诉我错误在哪里吗C# 如何将excel工作表中的数据导入sql server表?,c#,asp.net,sql,import-from-excel,C#,Asp.net,Sql,Import From Excel,嗨。我想将excel工作表数据导入SQL server表,为此我编写了如下代码。工作表正在上传到文件夹中,但数据没有导入到表中,有人能告诉我错误在哪里吗 public partial class upload2 : System.Web.UI.Page { private string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
public partial class upload2 : System.Web.UI.Page
{
private string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateDatabaseTables();
}
}
private void PopulateDatabaseTables()
{
string tableName = string.Empty;
string sql = "SELECT *, name AS table_name " +
" FROM sys.tables WHERE Type = 'U' ORDER BY table_name";
using (SqlConnection conn = new SqlConnection(connStr))
{
using (DataTable table = new DataTable())
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter(sql, conn))
{
dAd.Fill(table);
}
ListBox1.DataSource = table;
ListBox1.DataBind();
}
}
}
protected void ImportNow_Click(object sender, EventArgs e)
{
if (ListBox1.SelectedValue == "")
{
lblMessage.ForeColor = Color.Red;
lblMessage.Text = "Please select table in which you want to import data from excel sheet";
}
else if ((fileuploadExcel.FileName != ""))
{
string extension = Path.GetExtension(fileuploadExcel.PostedFile.FileName);
string excelConnectionString;
SqlConnection conn = new SqlConnection(connStr);
string tableName = ListBox1.SelectedValue;
// string path = fileuploadExcel.PostedFile.FileName;
string path = Server.MapPath("~/fileuploadExcel/" + fileuploadExcel.FileName);
fileuploadExcel.SaveAs(path);
Response.Write("path=" + path);
return;
//Create connection string to Excel work book
if (extension == ".xlsx")
{
excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=+ path +
;Extended Properties=Excel 8.0;Persist Security Info=False";
}
else
{
excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;sData Source= + path +
;Extended Properties=Excel 12.0;Persist Security Info=False";
}
//Create Connection to Excel work book
SqlConnection excelConnection = new SqlConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
conn.Open();
SqlCommand comm = new SqlCommand("truncate table " + tableName, conn);
SqlCommand identityChange = conn.CreateCommand();
identityChange.CommandText = "SET IDENTITY_INSERT " + tableName + " ON";
SqlCommand cmd = new SqlCommand("Select * from [Sheet1$]", excelConnection);
excelConnection.Open();
SqlDataReader dReader;
dReader = cmd.ExecuteReader();
identityChange.ExecuteNonQuery();
SqlBulkCopy sqlBulk = new SqlBulkCopy(connStr);
//Give your Destination table name
sqlBulk.DestinationTableName = tableName;
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
conn.Close();
lblMessage.ForeColor = Color.Green;
lblMessage.Text = "Import into table <b>" + tableName + "</b> successful!<br />";
}
else
{
lblMessage.ForeColor = Color.Red;
lblMessage.Text = "Please first upload (Select) excel file.";
}
}
protected void viewdata_Click(object sender, EventArgs e)
{
BindData();
}
private void BindData()
{
try
{
if (ListBox1.SelectedValue == "")
{
lblMessage.ForeColor = Color.Red;
lblMessage.Text = "Please select table for which you want to view data in Gridview";
}
else
{
string tableName = ListBox1.SelectedValue;
SqlConnection conn = new SqlConnection(connStr);
SqlDataAdapter sda = new SqlDataAdapter("select * from " + tableName, conn);
DataSet ds = new DataSet();
sda.Fill(ds);
gvdetails.DataSource = ds;
gvdetails.DataBind();
}
}
catch (DataException de)
{
lblMessage.Text = de.Message;
lblMessage.ForeColor = System.Drawing.Color.Red;
}
}
protected void gvdetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvdetails.PageIndex = e.NewPageIndex;
BindData();
}
}
}
public部分类上载2:System.Web.UI.Page
{
私有字符串connStr=ConfigurationManager.ConnectionString[“ConnectionString”].ConnectionString;
受保护的无效页面加载(对象发送方、事件参数e)
{
如果(!IsPostBack)
{
已填充的DatabaseTables();
}
}
private void PopulatedDatabaseTables()
{
string tableName=string.Empty;
string sql=“选择*,名称为表名称”+
“来自sys.tables,其中Type='U'按表名称排序”;
使用(SqlConnection conn=newsqlconnection(connStr))
{
使用(DataTable=newdatatable())
{
conn.Open();
使用(SqlDataAdapter dAd=newsqldataadapter(sql,conn))
{
爸爸。填写(表格);
}
ListBox1.DataSource=表;
ListBox1.DataBind();
}
}
}
受保护的void ImportNow_Click(对象发送方,事件参数e)
{
如果(ListBox1.SelectedValue==“”)
{
lblMessage.ForeColor=Color.Red;
lblMessage.Text=“请选择要从excel工作表导入数据的表”;
}
else if((fileuploadExcel.FileName!=“”)
{
字符串扩展名=Path.GetExtension(fileuploadExcel.PostedFile.FileName);
字符串excelConnectionString;
SqlConnection conn=新的SqlConnection(connStr);
string tableName=ListBox1.SelectedValue;
//字符串路径=fileuploadExcel.PostedFile.FileName;
字符串路径=Server.MapPath(“~/fileuploadExcel/”+fileuploadExcel.FileName);
fileuploadExcel.SaveAs(路径);
Response.Write(“path=“+path”);
返回;
//创建Excel工作簿的连接字符串
如果(扩展名=“.xlsx”)
{
excelConnectionString=@“Provider=Microsoft.Jet.OLEDB.4.0;数据源=+path+
;扩展属性=Excel 8.0;持久安全信息=False”;
}
其他的
{
excelConnectionString=@“Provider=Microsoft.ACE.OLEDB.12.0;sData源=+路径+
;扩展属性=Excel 12.0;持久安全信息=False”;
}
//创建到Excel工作簿的连接
SqlConnection excelConnection=新的SqlConnection(excelConnectionString);
//创建OleDbCommand以从Excel获取数据
conn.Open();
SqlCommand comm=新的SqlCommand(“截断表”+表名,conn);
SqlCommand identityChange=conn.CreateCommand();
identityChange.CommandText=“设置IDENTITY\u INSERT”+tableName+“ON”;
SqlCommand cmd=newsqlcommand(“从[Sheet1$]中选择*”,excelConnection);
excelConnection.Open();
SqlDataReader恐惧者;
dReader=cmd.ExecuteReader();
identityChange.ExecuteOnQuery();
SqlBulkCopy sqlBulk=新的SqlBulkCopy(connStr);
//给出目标表的名称
sqlBulk.DestinationTableName=tableName;
sqlBulk.WriteToServer(恐惧者);
excelConnection.Close();
康涅狄格州关闭();
lblMessage.ForeColor=Color.Green;
lblMessage.Text=“导入表格”+tableName+“成功!
”;
}
其他的
{
lblMessage.ForeColor=Color.Red;
lblMessage.Text=“请先上载(选择)excel文件。”;
}
}
受保护的无效视图数据\u单击(对象发送方,事件参数e)
{
BindData();
}
私有void BindData()
{
尝试
{
如果(ListBox1.SelectedValue==“”)
{
lblMessage.ForeColor=Color.Red;
lblMessage.Text=“请选择要在Gridview中查看其数据的表”;
}
其他的
{
string tableName=ListBox1.SelectedValue;
SqlConnection conn=新的SqlConnection(connStr);
SqlDataAdapter sda=新SqlDataAdapter(“从”+表名,conn中选择*);
数据集ds=新数据集();
sda.填充(ds);
gvdetails.DataSource=ds;
gvdetails.DataBind();
}
}
捕获(数据异常de)
{
lblMessage.Text=de.Message;
lblMessage.ForeColor=System.Drawing.Color.Red;
}
}
受保护的void gvdetails\u页面索引交换(对象发送方,GridViewPageEventArgs e)
{
gvdetails.PageIndex=e.NewPageIndex;
BindData();
}
}
}
为什么不使用MS SQL Server导入和导出向导。。
这是有史以来最简单的方法
参考此url,您就可以获得exect idea。
希望它能帮助您……为什么不使用MS SQL Server导入和导出向导。。 这是有史以来最简单的方法 参考此url,您就可以获得exect idea。 希望它能帮助您……excelConnectionString=@“Provider=Microsoft.Jet.OLE
excelConnectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}
;Extended Properties=Excel 8.0;Persist Security Info=False",path);
Provider=Microsoft.Jet.OLEDB.4.0;
Provider=Microsoft.ACE.OLEDB.12.0