市长热线演示版

callplanintophone.ashx.cs 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using HySoft.Common;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Data;
  9. using System.Data.SqlClient;
  10. using HySoft.DBUtility;
  11. using System.Data.OleDb;
  12. namespace HySoft.BaseCallCenter.Web.calloutmanage.ajax
  13. {
  14. /// <summary>
  15. /// callplanintophone 的摘要说明
  16. /// </summary>
  17. public class callplanintophone : IHttpHandler
  18. {
  19. public void ProcessRequest(HttpContext context)
  20. {
  21. context.Response.ContentType = "text/plain";
  22. string action = CommonRequest.GetQueryString("action");
  23. switch (action)
  24. {
  25. case "getfieldlist":
  26. getfieldlist(context);
  27. break;
  28. case "excelinto":
  29. ExcelInto(context);
  30. break;
  31. case "excelintodata":
  32. context.Response.Write(insertdata(context));
  33. break;
  34. }
  35. }
  36. private string insertdata(HttpContext context)
  37. {
  38. string res = "";
  39. string type = "0";
  40. int i = 1;
  41. try
  42. {
  43. string filepath = context.Request.Form["txtFilePath"].ToString();
  44. string columntofield = context.Request.Form["txtColumnToField"].ToString();
  45. string taskid = context.Request.Params["taskid"];
  46. #region 将文件中的数据导入数据库
  47. try
  48. {
  49. //************************将文件中的数据导入数据库*************************//
  50. DataSet dt = ReadEcxel(filepath, 0);
  51. int rcount = 0;
  52. int ccount = 0;
  53. try
  54. {
  55. if (dt != null && dt.Tables[0].Rows.Count != 0)
  56. {
  57. rcount = dt.Tables[0].Rows.Count;
  58. ccount = dt.Tables[0].Columns.Count;
  59. List<string> lstsql = new List<string>();
  60. foreach (DataRow dr in dt.Tables[0].Rows)
  61. {
  62. string[] arrfield = columntofield.Split(';');
  63. string sqlfield="";
  64. string sqlvalue = "";
  65. foreach (string fieldinfo in arrfield)
  66. {
  67. if (fieldinfo.Trim() != "")
  68. {
  69. string field = fieldinfo.Split(':')[0];
  70. string column = fieldinfo.Split(':')[1];
  71. sqlfield += field + ",";
  72. sqlvalue += "'" + dr[column].ToString().Trim().Replace(",", "").Replace("'", "") + "',";
  73. }
  74. }
  75. sqlfield += "#@!";
  76. sqlvalue += "#@!";
  77. sqlfield = sqlfield.Replace(",#@!", "").Replace("#@!", "");
  78. sqlvalue = sqlvalue.Replace(",#@!", "").Replace("#@!", "");
  79. lstsql.Add("INSERT INTO [T_Call_TaskTelNum]([F_TaskId]," + sqlfield + ")VALUES(" + taskid + "," + sqlvalue + ")");
  80. }
  81. int c = 0;
  82. using (SqlConnection coon = new SqlConnection(DbHelperSQL.connectionString))
  83. {
  84. c=DBUtility.DbHelperSQL.ExecuteSqlTran(lstsql, coon);
  85. type = "1";
  86. res = "导入成功,共导入" + c + "条;";
  87. }
  88. try
  89. {
  90. DBUtility.DbHelperSQL.ExecuteSql("update T_CTI_Task set y_HMCount=(y_HMCount+" + c + ") where TaskID=" + taskid);
  91. }
  92. catch { }
  93. }
  94. else
  95. {
  96. i++;
  97. res += i.ToString() + ".Excel或txt文本中无数据;";
  98. }
  99. }
  100. catch
  101. {
  102. i++;
  103. res += i.ToString() + ".导入出现异常,导入失败;";
  104. //File.Delete(filepath); //导入不成功时删除上传的excel文件
  105. }
  106. finally
  107. {
  108. dt.Clear();
  109. dt.Dispose();
  110. }
  111. KillProcess("Excel");//杀死已经打开的Excel进程
  112. }
  113. catch
  114. {
  115. i++;
  116. res += i.ToString() + ".Excel或txt文本格式不正确,系统错误,导入失败;";
  117. KillProcess("Excel");//杀死已经打开的Excel进程
  118. //File.Delete(filepath); //导入不成功时删除上传的excel文件
  119. }
  120. #endregion
  121. }
  122. catch(Exception ex)
  123. {
  124. res = ex.ToString();
  125. }
  126. return "{msg:" + type + ",info:\"" + res + "\"}";
  127. }
  128. private void getfieldlist(HttpContext context)
  129. {
  130. string strHtml = "";
  131. string strList = "";
  132. DataTable dt = new DataTable();
  133. try
  134. {
  135. string sql = " ";
  136. string taskid = "0";
  137. try
  138. {
  139. taskid = context.Request.Params["taskid"];
  140. if (taskid.Trim() != "")
  141. {
  142. sql += " and [F_TaskId]=" + taskid + " ";
  143. }
  144. else
  145. {
  146. sql += " and [F_TaskId]=0 ";
  147. }
  148. }
  149. catch
  150. { }
  151. BLL.T_Call_PageField bll = new BLL.T_Call_PageField();
  152. dt = bll.GetList(" 1=1 " + sql + " order by F_Sort ").Tables[0];
  153. if (dt.Rows.Count > 0)
  154. {
  155. for (int i = 0; i < dt.Rows.Count; i++)
  156. {
  157. strList += dt.Rows[i]["F_Id"] + ",";
  158. strHtml += "<div style=\"float:left; width:120px; height:80px; text-align:center; padding:6px;\">";
  159. strHtml += "<div style=\"height: 80px; border: 1px solid #CCCCCC; padding: 0px; text-align: center;\" onmouseover=\"this.style.border='1px solid #3A8BDC'\"";
  160. strHtml += "onmouseout=\"this.style.border='1px solid #CCCCCC'\">";
  161. strHtml += "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"";
  162. strHtml += "width=\"100%\" height=\"100%\" style=\" text-align:center;padding: 0px;\">";
  163. strHtml += "<tr><td style='background:#cccccc; color:red; height:30px;text-align:center;padding: 0px;'><input type=\"text\" id=\"txt_id_" + dt.Rows[i]["F_Id"].ToString() + "\" value='" + dt.Rows[i]["F_DBFieldlName"].ToString().Trim() + "' name=\"forcount\" style=\"display:none\" />";
  164. strHtml += "<span id=\"span_name_" + dt.Rows[i]["F_Id"].ToString() + "\">" + dt.Rows[i]["F_Name"].ToString() + "</span></td></tr>";
  165. strHtml += "<tr><td style='height:30px;text-align:center;padding: 0px;'><select id=\"select_column_" + dt.Rows[i]["F_Id"].ToString() + "\" style='width:100px; height:25px;' onfocus='InitExcelColumns(\"" + dt.Rows[i]["F_Id"].ToString() + "\")' ><option value=\"\"></option></select></td></tr></table></div></div>";
  166. }
  167. }
  168. strList += "!@#";
  169. strList = strList.Replace(",!@#", "").Replace("!@#", "");
  170. }
  171. catch
  172. {
  173. }
  174. finally
  175. {
  176. dt.Clear();
  177. dt.Dispose();
  178. }
  179. context.Response.Write(strList + "~" + strHtml);
  180. context.Response.End();
  181. }
  182. #region 杀死Excel进程
  183. /// <summary>
  184. /// 杀死Excel进程
  185. /// </summary>
  186. /// <param name="processName"></param>
  187. private void KillProcess(string processName)
  188. {
  189. System.Diagnostics.Process myproc = new System.Diagnostics.Process();
  190. //得到所有打开的进程
  191. try
  192. {
  193. foreach (Process thisproc in Process.GetProcessesByName(processName))
  194. {
  195. if (!thisproc.CloseMainWindow())
  196. {
  197. thisproc.Kill();
  198. }
  199. }
  200. }
  201. catch (Exception Exc)
  202. {
  203. throw new Exception("", Exc);
  204. }
  205. }
  206. #endregion
  207. #region 导入Excel表格
  208. protected void ExcelInto(HttpContext context)
  209. {
  210. string res = "";
  211. int i = 0;
  212. string Excelsource = "";
  213. HttpPostedFile _upfile = null;
  214. string strClNamelist = "";//列名称
  215. _upfile = context.Request.Files["txtUpload"];
  216. string filename = "";
  217. int rcount = 0;
  218. int ccount = 0;
  219. string filetype = "";
  220. try
  221. {
  222. //string fileType = _upfile.ContentType;
  223. string fileType = Path.GetExtension(_upfile.FileName.ToString().Trim());
  224. int type = fileType.IndexOf("xls");//application/vnd.ms-excel --//application/vnd
  225. if (type == -1)
  226. {
  227. type = fileType.IndexOf("xlsx");
  228. }
  229. else
  230. {
  231. filetype = "0";
  232. }
  233. if (type == -1)
  234. {
  235. type = fileType.IndexOf("txt");
  236. if (type == -1)
  237. {
  238. }
  239. else
  240. {
  241. filetype = "1";
  242. }
  243. }
  244. else
  245. {
  246. filetype = "0";
  247. }
  248. if (type == -1)
  249. {
  250. i++;
  251. res += i.ToString() + ".请选择正确的Excel或txt文本格式数据;";
  252. }
  253. else
  254. {
  255. string filePath = _upfile.FileName.ToString();
  256. int start = filePath.LastIndexOf("\\") + 1;
  257. int end = filePath.Length;
  258. filename = filePath.Substring(start, end - start);
  259. if (res == "")
  260. {
  261. try
  262. {
  263. KillProcess("Excel");//杀死已经打开的Excel进程
  264. if (_upfile.ContentLength > 0)
  265. {
  266. #region 上传excel文件
  267. //*********************上传excel文件**********************//
  268. string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssms");
  269. newFileName = newFileName + "_" + filename;
  270. try
  271. {
  272. if (!Directory.Exists(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + "\\ExcelData\\"+DateTime.Now.ToString("yyyyMM"))))
  273. {
  274. Directory.CreateDirectory(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + "\\ExcelData\\" + DateTime.Now.ToString("yyyyMM")));
  275. }
  276. _upfile.SaveAs(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + "\\ExcelData\\"+DateTime.Now.ToString("yyyyMM")+"\\") + newFileName.ToString());
  277. Excelsource = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath + "\\ExcelData\\"+DateTime.Now.ToString("yyyyMM")+"\\") + newFileName.ToString();
  278. }
  279. catch
  280. {
  281. i++;
  282. res = i.ToString() + ".上传Excel或txt文本数据时失败;";
  283. }
  284. #endregion
  285. if (res == "")
  286. {
  287. #region 将文件中的数据导入数据库
  288. try
  289. {
  290. //************************将文件中的数据导入数据库*************************//
  291. DataSet dt = ReadEcxel(Excelsource, 0);
  292. try
  293. {
  294. if (dt != null && dt.Tables[0].Rows.Count != 0)
  295. {
  296. if (res == "")
  297. {
  298. rcount = dt.Tables[0].Rows.Count;
  299. ccount = dt.Tables[0].Columns.Count;
  300. foreach (DataColumn dc in dt.Tables[0].Columns)
  301. {
  302. strClNamelist += "|" + dc.ColumnName;
  303. }
  304. if (strClNamelist != "")
  305. {
  306. strClNamelist = strClNamelist.Substring(1);
  307. }
  308. // dt.Tables[0].Columns;
  309. }
  310. }
  311. else
  312. {
  313. i++;
  314. res += i.ToString() + ".Excel或txt文本中无数据;";
  315. }
  316. }
  317. catch(Exception ex)
  318. {
  319. i++;
  320. res += i.ToString() + ".导入出现异常,导入失败;"+ex.Message.ToString();
  321. File.Delete(Excelsource); //导入不成功时删除上传的excel文件
  322. }
  323. finally
  324. {
  325. dt.Clear();
  326. dt.Dispose();
  327. }
  328. KillProcess("Excel");//杀死已经打开的Excel进程
  329. }
  330. catch (Exception ex)
  331. {
  332. i++;
  333. res += i.ToString() + ".Excel或txt文本格式不正确,系统错误,导入失败;" + ex.Message.ToString();
  334. KillProcess("Excel");//杀死已经打开的Excel进程
  335. File.Delete(Excelsource); //导入不成功时删除上传的excel文件
  336. }
  337. #endregion
  338. }
  339. }
  340. else
  341. {
  342. i++;
  343. res += i.ToString() + ".请选择上传文件;";
  344. }
  345. }
  346. catch
  347. {
  348. i++;
  349. res += i.ToString() + ".Excel或txt文本格式不正确,系统错误,导入失败;";
  350. KillProcess("Excel");//杀死已经打开的Excel进程
  351. }
  352. }
  353. else
  354. {
  355. i++;
  356. res = i.ToString() + "." + res + ";";
  357. }
  358. }
  359. }
  360. catch (Exception ex)
  361. {
  362. i++;
  363. res += i.ToString() + ".错误信息:" + ex.Message + ",导入失败;";
  364. KillProcess("Excel");//杀死已经打开的Excel进程
  365. if (File.Exists(Excelsource))
  366. {
  367. File.Delete(Excelsource); //导入不成功时删除上传的excel文件
  368. }
  369. }
  370. if (res != "")
  371. {
  372. string ms = "{msg:0,filename:\"" + filename + "\", filepath: \"" + Excelsource.Replace("\\", "\\\\") + "\",arrcolumn:\"" + strClNamelist + "\",filetype:\"" + filetype.Trim() + "\",info:\"" + res.Replace(".", "、").Replace(";", ";") + "\",msbox:\"" + res.Replace(".", "、").Replace(";", ";") + "\"}";
  373. context.Response.Write(ms);
  374. //context.Response.Write("{msg:0,msbox:\"" + res + "\"}");
  375. }
  376. else
  377. {
  378. string info = "本文件有" + rcount.ToString() + "行" + ccount.ToString() + "列数据";
  379. context.Response.Write("{msg:1,filename:\"" + filename + "\", filepath: \"" + Excelsource.Replace("\\", "\\\\") + "\",arrcolumn:\"" + strClNamelist + "\",filetype:\"" + filetype.Trim() + "\",info:\"" + info + "\"}");
  380. }
  381. }
  382. #endregion
  383. #region 读取Excel文件,返一个DataTable
  384. /// 功能:读取Excel文件,返一个DataTable
  385. /// 日期:2004-10-20
  386. /// </summary>
  387. /// <param name="FileName">文件</param>
  388. /// <param name="Rows">第一行是否为列名,一般为0或1</param>
  389. /// <returns></returns>
  390. private DataSet ReadEcxel(string FileName, int Rows)
  391. {
  392. return ToDataTable(FileName);
  393. //string _filePath = FileName;
  394. //string excelconnstring = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + "";
  395. ////HDR=NO; 读取数据表头(第一行);HDR=yes 不读取表头
  396. //excelconnstring += @";Extended Properties=""Excel 8.0;HDR=yes;IMEX=1""";
  397. //#region 判断excel格式xls或xlsx
  398. //string ext = Path.GetExtension(_filePath);
  399. //if (ext == "xlsx")
  400. //{
  401. // excelconnstring = "";
  402. //}
  403. //#endregion
  404. //System.Data.OleDb.OleDbConnection excelconn = new System.Data.OleDb.OleDbConnection(excelconnstring);
  405. //string sql = "select * from [sheet1$]";
  406. //System.Data.OleDb.OleDbDataAdapter mycomm = new System.Data.OleDb.OleDbDataAdapter(sql, excelconn);
  407. //DataSet myds = new DataSet();
  408. //mycomm.Fill(myds, "DataListTable");
  409. //return myds;
  410. }
  411. /// <summary>
  412. /// 读取Excel文件到DataSet中
  413. /// </summary>
  414. /// <param name="filePath">文件路径</param>
  415. /// <returns></returns>
  416. public DataSet ToDataTable(string filePath)
  417. {
  418. string connStr = "";
  419. string fileType = System.IO.Path.GetExtension(filePath);
  420. if (string.IsNullOrEmpty(fileType)) return null;
  421. if (fileType == ".xls")
  422. connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
  423. else
  424. connStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filePath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
  425. string sql_F = "Select * FROM [{0}]";
  426. OleDbConnection conn = null;
  427. OleDbDataAdapter da = null;
  428. DataTable dtSheetName = null;
  429. DataSet ds = new DataSet();
  430. try
  431. {
  432. // 初始化连接,并打开
  433. conn = new OleDbConnection(connStr);
  434. conn.Open();
  435. // 获取数据源的表定义元数据
  436. string SheetName = "";
  437. dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
  438. // 初始化适配器
  439. da = new OleDbDataAdapter();
  440. for (int i = 0; i < dtSheetName.Rows.Count; i++)
  441. {
  442. SheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];
  443. if (SheetName.Contains("$") && !SheetName.Replace("'", "").EndsWith("$"))
  444. {
  445. continue;
  446. }
  447. da.SelectCommand = new OleDbCommand(String.Format(sql_F, SheetName), conn);
  448. da.Fill(ds, "DataListTable");
  449. //DataSet dsItem = new DataSet();
  450. //da.Fill(dsItem, "DataListTable");
  451. //ds.Tables.Add(dsItem.Tables[0].Copy());
  452. break;
  453. }
  454. }
  455. catch (Exception ex)
  456. {
  457. SysLog.WriteLog(ex);
  458. }
  459. finally
  460. {
  461. // 关闭连接
  462. if (conn.State == ConnectionState.Open)
  463. {
  464. conn.Close();
  465. da.Dispose();
  466. conn.Dispose();
  467. }
  468. }
  469. return ds;
  470. }
  471. #endregion
  472. public bool IsReusable
  473. {
  474. get
  475. {
  476. return false;
  477. }
  478. }
  479. }
  480. }