本文共 3165 字,大约阅读时间需要 10 分钟。
#region 导入试题 ////// 导入按钮事件 /// /// /// protected void btnImport_Click(object sender, EventArgs e) { try { //获取题型 string strQuestionType = ddlQuestionType.SelectedItem.Text.Trim(); //获取表名 string strTableName = GetTableNameBLL.GetTableNameByCourseAndQuestionType(ddlCourse.CourseText.Trim(), strQuestionType, "1"); //检查文件是否存在 if (FileContainer.HasFile == false)//HasFile用来检查FileUpload是否有指定文件 { Alert("请选择Excel文件!"); return; } //获得文件的扩展名 string strFileType = System.IO.Path.GetExtension(FileContainer.FileName).ToString().ToLower(); if (strFileType != ".xls") { Alert("文件类型有误,请选择Excel文件!"); return;//当选择的不是Excel文件时,返回 } string strFileName = DateTime.Now.ToString("yyyymmddhhMMss") + FileContainer.FileName; //获取Execle文件名 DateTime日期函数 string savePath = Server.MapPath(("~\\Pages\\Excels\\") + strFileName);//Server.MapPath 获得虚拟服务器相对路径 //清理Excel文件夹 ClearFile(Server.MapPath("~\\Pages\\Excels")); //将上传的文件保存在服务器上 FileContainer.SaveAs(savePath); //将路径下的Excel文件转换为DataTable类型的数据源 DataTable dt = createDataSource(savePath); bool flag = BllImportExcel.Import(dt, strQuestionType, strTableName); //关掉Excel进程,否则导一次试题,内存占用量就越大 Process[] processes = System.Diagnostics.Process.GetProcesses(); Process process; for (int i = 0; i < processes.Length; i++) { process = processes[i]; if (process.ProcessName == "EXCEL") { process.Kill(); } } if (flag) { Alert("导入成功!"); } else { Alert("导入失败!"); } } catch { Alert("导入失败"); } }#endregion #region 将路径下的Excel文件转换为DataTable类型的数据源 ////// 将路径下的Excel文件转换为DataTable类型的数据源 /// /// 路径 ///private DataTable createDataSource(string strPath) { /** * 1、新建连接 * 2、绑定数据源 * 3、导出到Datatable * */ string strCon; strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strPath + ";Extended Properties=Excel 8.0"; OleDbConnection con = new OleDbConnection(strCon); OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1$]", con); DataTable dt = new DataTable(); da.Fill(dt); return dt; } #endregion #region 清理Excel文件夹 /// /// 当文件超过5个的时候,清理文件夹 /// /// private void ClearFile(string FilePath) { String[] files = System.IO.Directory.GetFiles(FilePath); if (files.Length > 5) { for (int i = 0; i < 5; i++) { try { System.IO.File.Delete(files[i]); } catch { } } } } #endregion
转载地址:http://mhdci.baihongyu.com/