今天,我们来试试看Excel文件怎么上传到指定的地方。
所用软件:
Microsoft Visual Studio 2010
SQL Server Management Studio
首先在数据库里面创建一个名为ErrorTemp的表做缓存功能。表如下:
ErrorTemp:
然后在VS里创建三层。然后上代码
Model层(userlist):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Model
{
public class userlist
{
public string datatype{set;get;}
public string errormsg {set;get;}
public string rows {set;get;}
public string userid { set; get; }
}
}
这是写底层数据库的对象(实例化对象)。
DAL层(TestDal):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace DAL
{
public class TestDal
{
public List<Model.userlist> ToSelect(string where)
{
DataSet ds = DB.ToGetData(" select * from ErrorTemp "+where);
if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
{
Model.userlist Myuserlist = null;
List<Model.userlist> MyList = new List<Model.userlist>();
foreach (DataRow item in ds.Tables[0].Rows)
{
Myuserlist = new Model.userlist();
Myuserlist.userid = item["userid"].ToString();
Myuserlist.errormsg = item["errormsg"].ToString();
Myuserlist.rows = item["rows"].ToString();
Myuserlist.datatype = item["datatype"].ToString();
MyList.Add(Myuserlist);
}
return MyList;
}
else
{
return null;
}
}
public int ToInsert(Model.userlist Swhere)
{
if (Swhere != null)
{
return DB. Tozhixing (" insert into ErrorTemp(userid,errormsg,rows,datatype) values ('" + Swhere.userid + "','" + Swhere.errormsg + "','" + Swhere.rows + "','" + Swhere.datatype + "')");
}
else
{
return 0;
}
}
public int ToDelete(string ID)
{
if (ID != null)
{
return DB. Tozhixing (" delete from ErrorTemp where userid= " + ID);
}
else
{
return 0;
}
}
public class DB
{
static string ConnStr = "Data Source=.;Initial Catalog=调用的数据库名?;Persist Security Info=True;User ID=数据库用户名;Password=数据库密码";
public static DataSet ToGetData(string Sql)
{
using (SqlConnection Conn = new SqlConnection(ConnStr))
{
using (SqlDataAdapter da = new SqlDataAdapter(Sql, Conn))
{
DataSet ds = new DataSet();
Conn.Open();
da.Fill(ds);
da.Dispose();
return ds;
}
}
}
public static int Tozhixing(string Sql)
{
using (SqlConnection Conn = new SqlConnection(ConnStr))
{
using (SqlCommand cmd = new SqlCommand(Sql, Conn))
{
Conn.Open();
int i = cmd.ExecuteNonQuery();
cmd.Dispose();
return i;
}
}
}
}
}
}
}
写底层基本调用,连接数据库
BLL(TestBll):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BLL
{
public class TestBll
{
DAL.TestDal MyTestDal = new DAL.TestDal();
public List<Model.userlist> GetUserByByUserIdAndDataType(string Id, string rows)
{
if (Id != null && rows != null)
{
return MyTestDal.ToSelect(" where userid='" + Id + "' and datatype='" + rows + "'");
}
else
{
return null;
}
}
public int ToInsert(Model.userlist Swhere)
{
if (Swhere != null)
{
return MyTestDal.ToInsert(Swhere);
}
else
{
return 0;
}
}
public int ToDelete(string ID,string where)
{
if (ID != null)
{
return MyTestDal.ToDelete(ID + "and datatype="+where);
}
else
{
return 0;
}
}
}
}
BLL层写各个需求。
UI(前端):
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Excel.aspx.cs" Inherits="UI.Excel" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head 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="上¦?传ä?" onclick="Button1_Click" />
</div>
</form>
</body>
</html>
前端两个控件
UI(后端):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Text.RegularExpressions;
namespace UI
{
public partial class Excel : System.Web.UI.Page
{
BLL.TestBll myuserbll = new BLL.TestBll();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
myuserbll.ToDelete(Session["Userid"].ToString(), "UserList");//删除临时错误信息表
if (FileUpload1.HasFile)
{
string FileName = FileUpload1.FileName;//获取文件名称(包括扩展名)
string FirstName = FileName.Substring(FileName.LastIndexOf("\\") + 1, (FileName.LastIndexOf(".") - FileName.LastIndexOf("\\") - 1)); //文件名
string LastName = FileName.Substring(FileName.LastIndexOf(".") + 1, (FileName.Length - FileName.LastIndexOf(".") - 1)); //扩展名
//判断是否是Excel文件
if (LastName.ToLower() == "xls" || LastName.ToLower() == "xlsx")
{
string SavePath = "Excel/UserList" + DateTime.Now.ToFileTime().ToString() + "." + LastName;//设置保存路劲
SavePath = Server.MapPath(SavePath);//路劲变成绝对路径
this.FileUpload1.SaveAs(SavePath); //上传文件
bool ishaveerror = ImportOrderExcelData(SavePath);
if (ishaveerror)
{
Page.ClientScript.RegisterStartupScript(GetType(), "js", "<script>alert('数据有误,请查看下面的错误列表!');</script>");
DataList1.DataSource = myuserbll.GetUserByByUserIdAndDataType(Session["Userid"].ToString(), "UserList");
DataList1.DataBind();
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "js", "<script>alert('数据上传成功!');window.location.href='UserList.aspx';</script>");
}
}
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "js", "<script>alert('请上传Excel文件!');window.location.href='UserList.aspx';</script>");
}
}
// <summary>
/// 导入Excel数据
/// </summary>
/// <param name="FilePath">Excel路径</param>
/// <param name="UserName">导入到数据库的表名</param>
/// <returns></returns>
public bool ImportOrderExcelData(string FilePath)
{
string strConn;
bool ishaveerror = false;
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FilePath + ";" + "Extended Properties=Excel 8.0; ";//初始化连接对象
using (OleDbConnection conn = new OleDbConnection())
{
OleDbDataAdapter oda = new OleDbDataAdapter("select * from [Sheet1$]", strConn);//读取Sheet1的数据
DataSet ds = new DataSet();
oda.Fill(ds, "ds");//存到缓存里面
oda.Dispose();
string UserName = "";
string UserPwd = "";
string RealName = "";
string MobilePhone = "";
Model.userlist MyTempError;
//循环缓存数据
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (i > 0)//表头数据无效
{
UserName = ds.Tables[0].Rows[i][0].ToString().Replace("'", "").Trim();//用户名
UserPwd = ds.Tables[0].Rows[i][1].ToString().Replace("'", "").Trim();//密码
RealName = ds.Tables[0].Rows[i][2].ToString().Replace("'", "").Trim();//真实姓名
MobilePhone = ds.Tables[0].Rows[i][3].ToString().Replace("'", "").Trim();//手机号
if (string.IsNullOrEmpty(UserName))
{
ishaveerror = true;
MyTempError = new Model.userlist();
MyTempError.datatype = "UserList";
MyTempError.errormsg = "请填写用户名";
MyTempError.rows = (i + 1) + "";
MyTempError.userid = Session["Userid"].ToString();
myuserbll.ToInsert(MyTempError);
}
else
{
//用户名格式判断[纯数字/纯英文/数字和英文的组合,6-16位]
//用户名判重
Regex regex = new Regex(@"(?i)^[a-z]\w{4,19}$");
return regex.IsMatch(UserName);
}
if (string.IsNullOrEmpty(UserPwd))
{
ishaveerror = true;
MyTempError = new Model.userlist();
MyTempError.datatype = "UserList";
MyTempError.errormsg = "请填写密码";
MyTempError.rows = (i + 1) + "";
MyTempError.userid = Session["Userid"].ToString();
myuserbll.ToInsert(MyTempError);
}
else
{
//密码格式判断[纯数字/纯英文/数字和英文的组合,6-16位]
Regex rgx = new Regex("^[\\w\\W]+$");//密码范围广
return rgx.IsMatch(UserPwd);
}
if (string.IsNullOrEmpty(RealName))
{
ishaveerror = true;
MyTempError = new Model.userlist();
MyTempError.datatype = "UserList";
MyTempError.errormsg = "请填写真实姓名";
MyTempError.rows = (i + 1) + "";
MyTempError.userid = Session["Userid"].ToString();
myuserbll.ToInsert(MyTempError);
}
if (string.IsNullOrEmpty(MobilePhone))
{
ishaveerror = true;
MyTempError = new Model.userlist();
MyTempError.datatype = "UserList";
MyTempError.errormsg = "请填写手机号码";
MyTempError.rows = (i + 1) + "";
MyTempError.userid = Session["Userid"].ToString();
myuserbll.ToInsert(MyTempError);
}
else
{
//手机格式判断
//手机号码判重
string dianxin = @"^1[3578][01379]\d{8}$";
Regex regexDX = new Regex(dianxin);
//联通手机号码正则
string liantong = @"^1[34578][01256]\d{8}";
Regex regexLT = new Regex(liantong);
//移动手机号码正则
string yidong = @"^(1[012345678]\d{8}|1[345678][012356789]\d{8})$";
Regex regexYD = new Regex(yidong);
if (regexDX.IsMatch(MobilePhone) || regexLT.IsMatch(MobilePhone) || regexYD.IsMatch(MobilePhone))
{
return true;
}
else
{
return false;
}
}
}
}
if (ishaveerror == false)
{
Model.userlist Myuser;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (i > 0)//表头数据无效
{
UserName = ds.Tables[0].Rows[i][0].ToString().Replace("'", "").Trim();//用户名
UserPwd = ds.Tables[0].Rows[i][1].ToString().Replace("'", "").Trim();//密码
RealName = ds.Tables[0].Rows[i][2].ToString().Replace("'", "").Trim();//真实姓名
MobilePhone = ds.Tables[0].Rows[i][3].ToString().Replace("'", "").Trim();//手机号
Myuser = new Model.userlist();
Myuser.datatype = MobilePhone;
Myuser.errormsg = UserPwd;
Myuser.rows = RealName;
Myuser.userid = MobilePhone;
myuserbll.ToInsert(Myuser);
}
}
}
ds.Dispose();
}
return ishaveerror;
}
}
}
后端正则判断
然后就可以发现上传的Excel文件可以上传到指定位置而且加上了日期自命名。
自觉的没什么卵用。
扫描二维码关注公众号,回复:
5061863 查看本文章