XLS表格导入数据库功能的实例代码
复制代码代码如下所示:protected void button1_click(object sender,EventArgs e)
{
如果(fileupload1.hasfile = false)
{
Page.Clientscript.RegisterStartupscript(this.gettype(),是否
返回;
}
字符串fileupload1.postedfile.filename; / /得到初始文件名
j = name.lastindexof(,); / / 得到最后的索引文件名。
newext1 =字符串名称。子(J); / /获取文件的扩展名
如果(newext1!=.xlsnewext1!=。xlsx )
{
Page.Clientscript.RegisterStartupscript(this.gettype(),稳健
返回;当选择不是Excel文件时,返回
}
SqlConnection CN =新的SqlConnection(ConfigurationManager里{连接字符串)));
打开();
/ /保存路径= path.getfullpath(fileupload1。postedfile。文件名); / /(fileupload1。postedfile。文件名的字符串);
如果(fileupload1.hasfile = = false) / / hasfile是用来检查文件上传文件
{
Page.Clientscript.RegisterStartupscript(this.gettype(),稳健
返回;当没有文件返回时
}
文件名= fileupload1.filename; / / path.getfilenamewithoutextension(fileupload1。postedfile。文件名);
保存路径= server.mappath((, / / / .. uploadfiles XLS / )+文件名);
fileupload1.saveas(保存路径); / /保存文件
DataSet ds = execleds(保存路径、文件名); / /调用自定义方法
DataRow { } = DS表{ 0 }。选择(DR); / /定义DataRow数组
国际rowsnum = DS表{ 0 }。rows.count;
如果(rowsnum = 0)
{
当Excel表为空时,提示用户
Page.Clientscript.RegisterStartupscript(this.gettype(),香港
}
其他的
{
对于(int = i 0;i <长度;i + +)
{
自定义模型学生
student.belong = ;
student.birthday = convert.todatetime(1990-1-1 );
student.classid = 1;
student.id = 1;
student.inschool = convert.todatetime(1990-1-1 );
student.phone = ;
student.sex = ;
student.type = ;
student.isaudite =没有;
student.roleid = convert.toint32(22 );
尝试
{
student.stuname = {我} {博士的名字ToString()};
student.stuid = {我} {博士学号} ToString();
student.username = {我} {博士的名字ToString()};
student.userpassword = {我} {博士学号} ToString();
}
catch(异常前){
响应。写入();
返回;
}
数据studentbll.getlist DS2 =(愚蠢的=+博士{我} {学号}。ToString()+);
如果(DS2。表{ 0 }。rows.count = 0)
{
尝试
{
布尔addStudent = convert.toboolean(studentbll.add(学生));
如果(addStudent)
Page.Clientscript.RegisterStartupscript(this.gettype(),道出
}
抓住(membershipcreateuserexception EX) / /捕捉异常
{
Page.Clientscript.RegisterStartupscript(this.gettype(),崇福
}
}
其他的
{
Page.Clientscript.RegisterStartupscript(this.gettype(),崇福
继续;
}
}
}
}
公共数据集(filenameurl execleds字符串,字符串表)
{
字符串strconn =商=微软。飞机。OLEDB。4;数据+ filenameurl +源=;扩展属性= 'excel 8;HDR =是的;该= 1;'; / /这弦音的错误或不空间
OleDbConnection conn =新OleDbConnection(strconn);
OleDbDataAdapter奥达=新数据适配器(SELECT * FROM { sheet18 $ },Conn); / / { sheet18 $ }是表名
数据集DS =新数据集();
奥达。填充(DS表);
返回DS;
}