Asp.net中把Excel数据存储至SQL Server中
操作图
ExcelWrapper
/// <summary>
/// 查询EXCEL电子表格添加到DATASET
/// </summary>
/// <param name="filenameurl">文件路径</param>
/// <param name="table">dataset中的表名(并不是要和数据库中的表一样)</param>
/// <returns></returns>
public static DataSet ExecleDs(string filenameurl, string table)
{
string strConn = "Provider=Microsoft.Jet.OleDb.4.0;"
+ "data source=" + filenameurl + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataSet ds = new DataSet();
OleDbDataAdapter odda = new OleDbDataAdapter("select * from [Sheet1$]", conn);
odda.Fill(ds, table);
return ds;
}
.cs
// 提交按钮
protected void imgbtnSubmit_Click(object sender, ImageClickEventArgs e)
{
try
{
if (!FileUpload1.HasFile)
{
JsHelper.Alert("请您选择Excel文件", this);
return;
}
// 取得文件后缀名
string extension = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
if (extension != ".xls" && extension != ".xlsx")
{
JsHelper.Alert("只可以选择Excel文件", this);
return;
}
// 构造Exel存在服务器相对路径的文件名,并SaveAs 将上传的文件内容保存在服务器上
string filename = DateTime.Now.ToString("yyyymmddhhMMss") + FileUpload1.FileName;
string savePath = Server.MapPath(("~\\upfiles\\") + filename);
FileUpload1.SaveAs(savePath);
DataSet ds = ExcelWrapper.ExecleDs(savePath, filename);
DataRow[] dr = ds.Tables[0].Select();
int rowsnum = ds.Tables[0].Rows.Count;
List<String> lstMsg = new List<string>();
if (rowsnum == 0)
{
JsHelper.Alert("Excel表为空表,无数据", this);
}
else
{
for (int i = 0; i < dr.Length; i++)
{
String error = "";
// excel列名不能变
string num = dr[i]["学号"].ToString();
string name = dr[i]["姓名"].ToString();
string pwd = dr[i]["密码"].ToString();
string collegeNum = dr[i]["学院编号"].ToString();
string birth = dr[i]["生日"].ToString();
if (!BLL.M_CollegeBLL.GetAllCollegeNum().Contains(collegeNum))
&nbs
补充:Web开发 , ASP.Net ,