在asp.net webfrom 中上传execl (读取单个sheet的数据)

protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == false)//HasFile用来检查FileUpload是否有指定文件
{
Response.Write(" ");
return;//当无文件时,返回
}
string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//System.IO.Path.GetExtension获得文件的扩展名
if (IsXls != ".xls" && IsXls != ".xlsm" && IsXls != ".xlsx")
{
Response.Write("");
return;//当选择的不是Excel文件时,返回
}
string filename = FileUpload1.FileName; //获取Execle文件名 DateTime日期函数
string savePath = Server.MapPath(("~\\Files\\") + filename);//Server.MapPath 获得虚拟服务器相对路径
FileUpload1.SaveAs(savePath); //SaveAs 将上传的文件内容保存在服务器上
DataSet ds = ExcelSqlConnection(savePath, filename); //调用自定义方法
if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0)
{
Response.Write(""); //当Excel表为空时,对用户进行提示
}
else
{
DataRow[] dr = ds.Tables[0].Select(); //定义一个DataRow数组
for (int i = 0; i < dr.Length; i++)
{
//前面除了你需要在建立一个“~\\Files\\”的文件夹外,其他的都不用管了,你只需要通过下面的方式获取Excel的值,然后再将这些值用你的方式去插入到数据库里面
string SKU = dr[i][0].ToString();
string UPC = dr[i][1].ToString();
string PRODUCT = dr[i][2].ToString();
string KIND = dr[i][3].ToString();
string PRODUCTDATE = dr[i][4].ToString();
Decimal EMAIL1 = Decimal.Parse(dr[i][5].ToString());
Decimal EMAIL2 = Decimal.Parse(dr[i][6].ToString());
Decimal EMAIL3 = Decimal.Parse(dr[i][7].ToString());
int PIECE = int.Parse(dr[i][8].ToString());
float WEIGHT = float.Parse(dr[i][9].ToString());
string ckdm = dr[i][10].ToString();
try
{
using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(Connectionstring()))
{
conn.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.Connection = conn;
string sql = @"insert into TBifaceSKU (SKU,UPC,PRODUCT,KIND,PRODUCTDATE,EMAIL1,EMAIL2,EMAIL3,PIECE,WEIGHT,ckdm)
VALUES('" + SKU + "','" + UPC + "','" + PRODUCT + "','" + KIND + "','" + PRODUCTDATE + "'," + EMAIL1 + "," + EMAIL2 + "," + EMAIL3 + "," + PIECE + "," + WEIGHT + ",'" + ckdm + "') ";
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}

}
catch (Exception ex)
{
Response.Write("");
}

}
Response.Write("");
}
}

 

 

 

 

#region 连接Excel 读取Excel数据 并返回DataSet数据集合
///


/// 连接Excel 读取Excel数据 并返回DataSet数据集合
///

/// Excel服务器路径
/// Excel表名称
///
public static System.Data.DataSet ExcelSqlConnection(string filepath, string tableName)
{
string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
OleDbConnection ExcelConn = new OleDbConnection(strCon);
try
{
string strCom = string.Format("SELECT * FROM [Sheet1$]");
ExcelConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, ExcelConn);
DataSet ds = new DataSet();
myCommand.Fill(ds, "[" + tableName + "$]");
ExcelConn.Close();
return ds;
}
catch
{
ExcelConn.Close();
return null;
}
}
#endregion

转载于:https://www.cnblogs.com/hbh123/p/5130881.html

你可能感兴趣的:(数据库)