前台代码:
店铺:
|
|
工作表名称:
|
|
|
|
|
后台代码:
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = Server.HtmlEncode(FileUpload1.FileName);
string extension = System.IO.Path.GetExtension(fileName);
if ((extension == ".xlsx") || (extension == ".xls"))
{
ExalToSql();
}
}
}
private void ExalToSql()
{
string sheet = "";
string path = Server.MapPath(FileUpload1.FileName);
FileUpload1.PostedFile.SaveAs(path);//保存文件
//string connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " + path + ";Extended Properties =Excel 12.0;HDR=YES;IMEX=1;";
string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";Extended Properties='Excel 8.0;'";
//建立EXCEL的连接
OleDbConnection objConn = new OleDbConnection(sConnectionString);
int count = 0;//用来记录出错的条数
try
{
if (string.IsNullOrWhiteSpace(txtSheet.Text))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "startup", "");
}
else
{
sheet = txtSheet.Text.Trim();
}
string strCom = " SELECT * FROM [" + sheet + "$A1:E100] ";
objConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, objConn);
DataSet ds = new DataSet();
myCommand.Fill(ds, "[" + sheet + "$]");
DataTable dt = ds.Tables[0];
string query = "select count(*) from CustomerServiceMonth where seller_id='" + ddlSeller.SelectedItem.Value + "'";
int customercount = int.Parse(SQLDBHelper.GetSingle(query).ToString());
if (customercount > 0)
{
string delete = "delete from Customer where seller_id='" + ddlSeller.SelectedItem.Value + "' and monthOfDate=" + DateTime.Now.Month;
SQLDBHelper.ExecuteSql(delete);
}
foreach (DataRow myDrv in dt.Rows)
{
count++;
if (!string.IsNullOrWhiteSpace(myDrv[1].ToString().Trim()))
{
string sql = @"INSERT INTO Customer
([ww_nick]
,[ww_successRate]
,[seller_id]
,[ww_unitPrice]
,[ww_sale]
,[monthOfDate]
,[modified]
,[salrate])
VALUES
('" + myDrv[0].ToString().Trim()
+ "','" + myDrv[1].ToString().Trim()
+ "','" + ddlSeller.SelectedItem.Value
+ "','" + myDrv[2].ToString().Trim()
+ "','" + myDrv[3].ToString().Trim()
+ "'," + DateTime.Now.Month
+ ",'" + DateTime.Now
+ "','" + myDrv[4].ToString().Trim() + "')";
SQLDBHelper.ExecuteSql(sql);
}
}
gvImport.DataSource = ds;
gvImport.DataBind();
}
catch
{
Page.Response.Write("alert('第" + count.ToString() + "条数据出错!');");
}
finally
{
objConn.Close();//关闭EXCEL的连接
}
}