以下例子转载:互联网
先在类中定义一个方法名为ExecleDs的方法,用于将Excel表里的数据填充到DataSet中,代码如下
public DataSet ExecleDs(string filenameurl,string table)
2 {
3 string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" +filenameurl+ ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
4 OleDbConnection conn = new OleDbConnection(strConn);
5
6 OleDbDataAdapter odda = new OleDbDataAdapter("select * from [Sheet1$]",conn);
7 DataSet ds = new DataSet();
8 odda.Fill(ds,table);
9
10 return ds;
11
12 }
然后设计页面,在此作个简单的页面
<table style=" 395px; height: 84px" border="1">
2 <tr>
3 <td style="380px" align="center">
4 批量导入用户信息</td>
5 </tr>
6 <tr>
7 <td style=" 100px">
8 <asp:FileUpload ID="FileUpload1" runat="server" Width="380px" /></td>
9 </tr>
10 <tr>
11 <td style="380px" align="center">
12 <asp:Button ID="Button1" runat="server" Text="添加" OnClick="Button1_Click" /></td>
13 </tr>
14 </table>
15 <asp:Label ID="Label1" runat="server" Width="466px"></asp:Label>
当点击添加按钮时激发事件,代码如下
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == false)
{
Response.Write("<script>alert('请您选择Excel文件')</script> ");
return;//当无文件时,返回
}
string IsXls=System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
if (IsXls != ".xls")
{
Response.Write("<script>alert('只可以选择Excel文件')</script>");
return;//当选择的不是Excel文件时,返回
}
string error = null;
Access.Class1 ac = new Access.Class1();
SqlConnection cn = ac.myConnection();
cn.Open();
string strpath = FileUpload1.PostedFile.FileName.ToString(); //获取Execle文件路径
string filename = FileUpload1.FileName; //获取Execle文件名
DataSet ds = ac.ExecleDs(strpath,filename);
DataRow[] dr = ds.Tables[0].Select(); //定义一个DataRow数组
int rowsnum = ds.Tables[0].Rows.Count;
if (rowsnum == 0)
{
Response.Write("<script>alert('Excel表为空表,无数据!')</script>"); //当Excel表为空时,对用户进行提示
}
else
{
for (int i = 0; i < dr.Length; i++)
{
string YHMC = dr[i]["YongHuMingCheng"].ToString();
string YHMM = dr[i]["YongHuMiMa"].ToString();
string DQRQ = dr[i]["DaoQiRiQi"].ToString();
string ZT = dr[i]["ZhuangTai"].ToString();
string TJSJ = dr[i]["TianJiaShiJian"].ToString();
string JXDM = dr[i]["JiaXiaoDaiMa"].ToString();
string sqlcheck = "select count(*) from DC_YongHuLieBiao where YongHuMingCheng='" + YHMC +"'And JiaXiaoDaiMa='" + JXDM + "'"; //检查用户是否存在
bool ch = ac.check(sqlcheck);
if (ch == true)
{
string insertstr = "insert into DC_YongHuLieBiao(YongHuMingCheng,YongHuMiMa,DaoQiRiQi,ZhuangTai,TianJiaShiJian,JiaXiaoDaiMa) values('" +
YHMC + "','" + YHMM + "','" + DQRQ + "','" + ZT + "','" + TJSJ + "','" + JXDM + "')";
SqlCommand cmd = new SqlCommand(insertstr,cn);
try
{
cmd.ExecuteNonQuery();
} catch (MembershipCreateUserException ex) //捕捉异常
{
Response.Write("<script>alert('创建用户:"+ex.Message+"')</script>");
}
}
else
{
error += "<em style='color:red;font-sixe:25px'>"+YHMC+"</em>用户已存在,此行记录无法插入!请修改用户再进行插入 <br>"; //若用户存在,将已存在用户信息打出,并提示此用户无法插入
continue;
}
}
Response.Write("<script>alert('Excle表导入成功!')</script>");
Label1.Text = error;
}
cn.Close();
}