.net导入Excel 并显示进度条
在程序開發(fā)過程中,往往會(huì)涉及到將Excel表格導(dǎo)入到數(shù)據(jù)庫中的需求,而當(dāng)excel表格內(nèi)容很多的時(shí)候,我們往往會(huì)很難去捕捉它的執(zhí)行過程進(jìn)度和一些錯(cuò)誤信息,此時(shí)我們便可以通過以下方法去解決這些難題,具體實(shí)現(xiàn)過程分析如下:
一、建立一個(gè)web應(yīng)用程序,在程序中首先創(chuàng)建一個(gè)html文件命名為ProgressBar,文件內(nèi)容如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
?//開始處理
function BeginTrans(msg) {
?WriteText(msg);
?}
//設(shè)置進(jìn)度條進(jìn)度
?function SetPorgressBar(msg, pos) {
? ? ? ? ProgressBar.style.width = pos + "%";
? ? ? ? WriteText(msg + " 已完成" + pos + "%");
? ? }
? ? //處理結(jié)束
function EndTrans(msg) {
if (msg == "")
WriteText("完成。");
?else
?WriteText(msg);
? }
? ? //設(shè)置時(shí)間信息
? ? 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>
二、創(chuàng)建一個(gè)aspx頁面,前后端代碼分別如下:
//1.這里為了簡便,我只寫出了前端頁面中的body體部分供參考:
<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="導(dǎo)入" Width="60px" οnclick="Button1_Click"/></td>
</tr>
</table>
</form>
//2.后端部分代碼如下:
?//這里是激發(fā)導(dǎo)入按鈕點(diǎn)擊事件
? ? ? ? protected void Button1_Click(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? string cfilename = this.fuGlossaryXls.FileName;//獲取準(zhǔn)備導(dǎo)入的文件名稱
? ? ? ? ? ? if (cfilename == "")
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Label2.Visible = true;
? ? ? ? ? ? ? ? return;
? ? ? ? ? ? }
? ? ? ? ? ? else
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Label2.Visible = false;
? ? ? ? ? ? }
? ? ? ? ? ? //顯示進(jìn)度/
? ? ? ? ? ? DateTime startTime = System.DateTime.Now;
? ? ? ? ? ? DateTime endTime = System.DateTime.Now;
? ? ? ? ? ? // 根據(jù) ProgressBar.htm 顯示進(jìn)度條界面
? ? ? ? ? ? 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('正在加載數(shù)據(jù),請耐心等待...');</script>";
? ? ? ? ? ? Response.Write(jsBlock);
? ? ? ? ? ? Response.Flush();
? ? ? ? ? ? ?string fileName = fuGlossaryXls.PostedFile.FileName.Substring(fuGlossaryXls.PostedFile.FileName.LastIndexOf("\\") + 1);//獲取準(zhǔn)備導(dǎo)入文件的文件名
? ? ? ? ? ? ?string suffix = fileName.Substring(fileName.LastIndexOf(".") + 1);//獲取準(zhǔn)備導(dǎo)入文件的后綴名
? ? ? ? ? ? ?System.Threading.Thread.Sleep(200);
? ? ? ? ? ? ?int maxrows = 0;//用來記錄需要加載的數(shù)據(jù)總行數(shù)
? ? ? ? ? ? ?bool err = false;//用來記錄加載狀態(tài)
? ? ? ? ? ? ?int errcount = 0;//用來記錄加載錯(cuò)誤行數(shù)
? ? ? ? ? ? ?if (fuGlossaryXls.HasFile)//判斷當(dāng)前是否有選取文件
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?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 條件的數(shù)據(jù)行
? ? ? ? ? ? ? ? ? ? ?//拓展
? ? ? ? ? ? ? ? ? ? ?string sqlconnect = "Data Source=.;Initial Catalog=test;User ID=sa;Password=123456;";//本地?cái)?shù)據(jù)庫鏈接
? ? ? ? ? ? ? ? ? ? ?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();//首先執(zhí)行清除表內(nèi)容操作
? ? ? ? ? ? ? ? ? ? ? ? ?for (int j = 0; j < dt.Rows.Count; j++)//循環(huán)向數(shù)據(jù)庫中插入excel數(shù)據(jù)
? ? ? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?if (string.IsNullOrEmpty(dt.Rows[j][0].ToString()))
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?jsBlock = "<script>EndTrans('第" + j.ToString() + "行數(shù)據(jù)寫入錯(cuò)誤。');</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();//逐行向表中插入數(shù)據(jù),注意字段的對應(yīng)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?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();//關(guān)閉數(shù)據(jù)庫連接
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ?else
? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ?ClientScript.RegisterStartupScript(GetType(), "", "alert('請選擇Excel文件!');", true);
? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ?}
? ? ? ? ? ? ?else
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?ClientScript.RegisterStartupScript(GetType(), "", "alert('請選擇要導(dǎo)入的Excel!');", true);
? ? ? ? ? ? ?}
? ? ? ? ? ? ?if (!err)//加載中并沒有出現(xiàn)錯(cuò)誤
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?// 處理完成
? ? ? ? ? ? ? ? ?jsBlock = "<script>EndTrans('處理完成。');</script>";
? ? ? ? ? ? ? ? ?Response.Write(jsBlock);
? ? ? ? ? ? ? ? ?Response.Flush();
? ? ? ? ? ? ?}
? ? ? ? ? ? ?else
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?jsBlock = "<script>EndTrans('共有"+maxrows.ToString()+"條數(shù)據(jù)需要加載,其中 有"+errcount.ToString()+"條數(shù)據(jù)錄入錯(cuò)誤!');</script>";
? ? ? ? ? ? ? ? ?Response.Write(jsBlock);
? ? ? ? ? ? ? ? ?Response.Flush();
? ? ? ? ? ? ?}
? ? ? ? ? ? ?System.Threading.Thread.Sleep(1000);
? ? ? ? ? ? ?endTime = DateTime.Now;//錄入完成所用時(shí)間
? ? ? ? ? ? ?TimeSpan ts1 = new TimeSpan(startTime.Ticks);
? ? ? ? ? ? ?TimeSpan ts2 = new TimeSpan(endTime.Ticks);
? ? ? ? ? ? ?TimeSpan ts = ts2.Subtract(ts1).Duration(); //取開始時(shí)間和結(jié)束時(shí)間兩個(gè)時(shí)間差的絕對值
? ? ? ? ? ? ?String spanTime = ts.Hours.ToString() + "小時(shí)" + ts.Minutes.ToString() + "分" + ts.Seconds.ToString() + "秒";
? ? ? ? ? ? ?jsBlock = "<script>SetTimeInfo('加載完成,共用時(shí)" + spanTime + "');</script>";
? ? ? ? ? ? ?Response.Write(jsBlock);
? ? ? ? ? ? ?Response.Flush();
? ? ? ? }
? ? ? ? public DataTable ExcelImport(string fileName) //建立Excel表鏈接,返回Excel表數(shù)據(jù)
? ? ? ? {
? ? ? ? ? ? ? ? //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的連接
//說明:程序運(yùn)行到這里的時(shí)候有時(shí)會(huì)出錯(cuò)“未在本地計(jì)算機(jī)上注冊“Microsoft.ACE.OLEDB.12.0”提供程序”,此時(shí)大多數(shù)情況下我們只需要去http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c-4e19-b0da-1463960fdcdb/AccessDatabaseEngine.exe下載一個(gè)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();//關(guān)閉EXCEL的連接
? ? ? ? ? ? ? ? return dt;
}
這個(gè)是程序測試中使用的excel表格實(shí)例。
總結(jié)
以上是生活随笔為你收集整理的.net导入Excel 并显示进度条的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WinCC RT Adv 项目下载与自动
- 下一篇: Ajax上传文件(视频),并获取上传进度