进度条在.net导入Excel时的应用实例
本文实例讲述了进度条在.net导入excel时的应用,分享给大家供大家参考。具体实现方法如下:
在程序开发过程中,往往会涉及到将excel表格导入到数据库中的需求,而当excel表格内容很多的时候,我们往往会很难去捕捉它的执行过程进度和一些错误信息,此时我们便可以通过以下方法去解决这些难题,具体实现过程分析如下:
一、建立一个web应用程序,在程序中首先创建一个html文件命名为progressbar,文件内容如下:
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
//开始处理
function begintrans(msg) {
writetext(msg);
}
//设置进度条进度
function setporgressbar(msg, pos) {
progressbar.style.width = pos + "%";
writetext(msg + " 已完成" + pos + "%");
}
//处理结束
function endtrans(msg) {
if (msg == "")
writetext("完成。");
else
writetext(msg);
}
//设置时间信息
function settimeinfo(msg) {
writetext(msg);
}
// 更新文本显示信息
function writetext(str) {
var strtag = '<font face="verdana, arial, helvetica" size="2" color="#ea9b02"><b>' + str + '</b></font>';
document.getelementbyid("msg2").innerhtml = strtag;
}
</script>
</head>
<body>
<table align="center" style="height:100%">
<tr style="height:45%"><td></td></tr>
<tr>
<td>
<div id="progressbarside" style="width:300px; color:silver;border-width:1px; border-style:solid;">
<div id="progressbar" align="center" style="height:20px; width:0%; background-color:#316ac5;"></div>
</div>
</td>
<td>
<div id="msg2" style="height:16px;"></div>
</td>
</tr>
<tr style="height:50%"><td></td></tr>
</table>
</body>
</html>
二、创建一个aspx页面,前后端代码分别如下:
<form id="forms" runat = "server">
<table align="center" style="height:100%">
<tr style="height:45%"><td></td></tr>
<tr>
<td align="center" style="height: 24px; width: 100px;"> excel文件</td>
<td style="height: 24px">
<asp:fileupload id="fuglossaryxls" runat="server"/>
<asp:label id="label2" runat="server" font-bold="true" forecolor="red" text="不能为空"
visible="false"></asp:label></td>
<td>
<asp:button id="button1" runat="server" cssclass="mybotton" text="导入" width="60px" onclick="button1_click"/></td>
</tr>
</table>
</form>
//2.后端部分代码如下:
//这里是激发导入按钮点击事件
protected void button1_click(object sender, eventargs e)
{
string cfilename = this.fuglossaryxls.filename;//获取准备导入的文件名称
if (cfilename == "")
{
label2.visible = true;
return;
}
else
{
label2.visible = false;
}
//////////////显示进度/////////////////////////////////////////////////////////////////////////////
datetime starttime = system.datetime.now;
datetime endtime = system.datetime.now;
// 根据 progressbar.htm 显示进度条界面
string templatefilename = path.combine(server.mappath("."), "progressbar.htm");
streamreader reader = new streamreader(@templatefilename, system.text.encoding.getencoding("gb2312"));
string html = reader.readtoend();
reader.close();
response.write(html);
response.flush();
system.threading.thread.sleep(1000);
string jsblock;
// 处理完成
jsblock = "<script>begintrans('正在加载数据,请耐心等待...');</script>";
response.write(jsblock);
response.flush();
string filename = fuglossaryxls.postedfile.filename.substring(fuglossaryxls.postedfile.filename.lastindexof("\\") + 1);//获取准备导入文件的文件名
string suffix = filename.substring(filename.lastindexof(".") + 1);//获取准备导入文件的后缀名
system.threading.thread.sleep(200);
int maxrows = 0;//用来记录需要加载的数据总行数
bool err = false;//用来记录加载状态
int errcount = 0;//用来记录加载错误行数
if (fuglossaryxls.hasfile)//判断当前是否有选取文件
{
if (suffix == "xlsx")
{
datatable dt = excelimport(filename);
for (int i = 0; i < dt.rows.count; i++)
{
maxrows++;
}
//////////拓展////////////////////////////////////////////////////////
//dataview myview = new dataview(dt);
//myview.rowfilter = "name is not null";
//int t = myview.count;//获取满足rowfilter 条件的数据行
//////////拓展////////////////////////////////////////////////////////
string sqlconnect = "data source=.;initial catalog=test;user id=sa;password=123456;";//本地数据库链接
sqlconnection conn = new sqlconnection(sqlconnect);
sqltransaction mytrans = null;
try
{
sqlcommand cmd = new sqlcommand(null, conn);
conn.open();
mytrans = conn.begintransaction();
cmd.transaction = mytrans;
cmd.commandtext = "delete from test";
cmd.executenonquery();//首先执行清除表内容操作
for (int j = 0; j < dt.rows.count; j++)//循环向数据库中插入excel数据
{
if (string.isnullorempty(dt.rows[j][0].tostring()))
{
jsblock = "<script>endtrans('第" + j.tostring() + "行数据写入错误。');</script>";
response.write(jsblock);
response.flush();
err = true;
errcount++;
}
else
{
cmd.commandtext = string.format("insert into test values('{0}','{1}','{2}','{3}')", dt.rows[j][0], dt.rows[j][1], dt.rows[j][2], dt.rows[j][3]);
cmd.executenonquery();//逐行向表中插入数据,注意字段的对应
}
system.threading.thread.sleep(1000);
float cposf = 0;
cposf = 100 * (j + 1) / maxrows;
int cpos = (int)cposf;
jsblock = "<script>setporgressbar('已加载到第" + (j + 1).tostring() + "条','" + cpos.tostring() + "');</script>";
response.write(jsblock);
response.flush();
}
mytrans.commit();//提交
}
catch (exception ex)
{
mytrans.rollback();//回滚
clientscript.registerstartupscript(this.gettype(), "alert", "<script>alert('" + ex.message + "');</script>");
}
finally
{
conn.dispose();
conn.close();//关闭数据库连接
}
}
else
{
clientscript.registerstartupscript(gettype(), "", "alert('请选择excel文件!');", true);
}
}
else
{
clientscript.registerstartupscript(gettype(), "", "alert('请选择要导入的excel!');", true);
}
if (!err)//加载中并没有出现错误
{
// 处理完成
jsblock = "<script>endtrans('处理完成。');</script>";
response.write(jsblock);
response.flush();
}
else
{
jsblock = "<script>endtrans('共有"+maxrows.tostring()+"条数据需要加载,其中 有"+errcount.tostring()+"条数据录入错误!');</script>";
response.write(jsblock);
response.flush();
}
system.threading.thread.sleep(1000);
endtime = datetime.now;//录入完成所用时间
timespan ts1 = new timespan(starttime.ticks);
timespan ts2 = new timespan(endtime.ticks);
timespan ts = ts2.subtract(ts1).duration(); //取开始时间和结束时间两个时间差的绝对值
string spantime = ts.hours.tostring() + "小时" + ts.minutes.tostring() + "分" + ts.seconds.tostring() + "秒";
jsblock = "<script>settimeinfo('加载完成,共用时" + spantime + "');</script>";
response.write(jsblock);
response.flush();
}
public datatable excelimport(string filename) //建立excel表链接,返回excel表数据
{
//excel 的连接串
string sconnectionstring = "provider=microsoft.ace.oledb.12.0;" +
"data source=c:\\documents and settings\\administrator\\桌面\\" + filename + ";" +
"extended properties='excel 8.0;imex=1';";
//string sconnectionstring = "microsoft.ace.oledb.4.0;" +
//"data source=c:\\documents and settings\\administrator\\桌面\\" + filename + ";" +
//"extended properties='excel 8.0;imex=1';";
oledbconnection objconn = new oledbconnection(sconnectionstring);//建立excel的连接
//说明:程序运行到这里的时候有时会出错“未在本地计算机上注册“microsoft.ace.oledb.12.0”提供程序”,此时大多数情况下我们只需要去http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/accessdatabaseengine.exe下载一个accessdatabaseengine.exe安装即可,原因在于你的office没有安装access组件
objconn.open();
oledbcommand objcmdselect = new oledbcommand("select * from [sheet1$]", objconn);
oledbdataadapter objadapter1 = new oledbdataadapter();
objadapter1.selectcommand = objcmdselect;
dataset objdataset1 = new dataset();
objadapter1.fill(objdataset1, "xldata");
datatable dt = objdataset1.tables[0];
//dataview myview = new dataview(dt);
objconn.close();//关闭excel的连接
return dt;
}
三、项目执行过程中的效果图展示如下:
这个是程序测试中使用的excel表格实例。
希望本文所述对大家的.net程序设计有所帮助。