DataToExcel.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. using System;
  2. using System.Diagnostics;
  3. //using Excel;
  4. namespace Ant.Service.Utilities
  5. {
  6. /// <summary>
  7. /// 操作EXCEL导出数据报表的类
  8. /// </summary>
  9. public class DataToExcel
  10. {
  11. public DataToExcel()
  12. {
  13. }
  14. #region 操作EXCEL的一个类(需要Excel.dll支持)
  15. private int titleColorindex = 15;
  16. /// <summary>
  17. /// 标题背景色
  18. /// </summary>
  19. public int TitleColorIndex
  20. {
  21. set { titleColorindex = value; }
  22. get { return titleColorindex; }
  23. }
  24. private DateTime beforeTime; //Excel启动之前时间
  25. private DateTime afterTime; //Excel启动之后时间
  26. #region 创建一个Excel示例
  27. /// <summary>
  28. /// 创建一个Excel示例
  29. /// </summary>
  30. public void CreateExcel()
  31. {
  32. //Excel.Application excel = new Excel.Application();
  33. //excel.Application.Workbooks.Add(true);
  34. //excel.Cells[1, 1] = "第1行第1列";
  35. //excel.Cells[1, 2] = "第1行第2列";
  36. //excel.Cells[2, 1] = "第2行第1列";
  37. //excel.Cells[2, 2] = "第2行第2列";
  38. //excel.Cells[3, 1] = "第3行第1列";
  39. //excel.Cells[3, 2] = "第3行第2列";
  40. ////保存
  41. //excel.ActiveWorkbook.SaveAs("./tt.xls", XlFileFormat.xlExcel9795, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
  42. ////打开显示
  43. //excel.Visible = true;
  44. //// excel.Quit();
  45. //// excel=null;
  46. //// GC.Collect();//垃圾回收
  47. }
  48. #endregion
  49. #region 将DataTable的数据导出显示为报表
  50. /// <summary>
  51. /// 将DataTable的数据导出显示为报表
  52. /// </summary>
  53. /// <param name="dt">要导出的数据</param>
  54. /// <param name="strTitle">导出报表的标题</param>
  55. /// <param name="FilePath">保存文件的路径</param>
  56. /// <returns></returns>
  57. //public string OutputExcel(System.Data.DataTable dt, string strTitle, string FilePath)
  58. //{
  59. // beforeTime = DateTime.Now;
  60. // Excel.Application excel;
  61. // Excel._Workbook xBk;
  62. // Excel._Worksheet xSt;
  63. // int rowIndex = 4;
  64. // int colIndex = 1;
  65. // excel = new Excel.ApplicationClass();
  66. // xBk = excel.Workbooks.Add(true);
  67. // xSt = (Excel._Worksheet)xBk.ActiveSheet;
  68. // //取得列标题
  69. // foreach (DataColumn col in dt.Columns)
  70. // {
  71. // colIndex++;
  72. // excel.Cells[4, colIndex] = col.ColumnName;
  73. // //设置标题格式为居中对齐
  74. // xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).Font.Bold = true;
  75. // xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;
  76. // xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).Select();
  77. // xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).Interior.ColorIndex = titleColorindex;//19;//设置为浅黄色,共计有56种
  78. // }
  79. // //取得表格中的数据
  80. // foreach (DataRow row in dt.Rows)
  81. // {
  82. // rowIndex++;
  83. // colIndex = 1;
  84. // foreach (DataColumn col in dt.Columns)
  85. // {
  86. // colIndex++;
  87. // if (col.DataType == System.Type.GetType("System.DateTime"))
  88. // {
  89. // excel.Cells[rowIndex, colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
  90. // xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐
  91. // }
  92. // else
  93. // if (col.DataType == System.Type.GetType("System.String"))
  94. // {
  95. // excel.Cells[rowIndex, colIndex] = "'" + row[col.ColumnName].ToString();
  96. // xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐
  97. // }
  98. // else
  99. // {
  100. // excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
  101. // }
  102. // }
  103. // }
  104. // //加载一个合计行
  105. // int rowSum = rowIndex + 1;
  106. // int colSum = 2;
  107. // excel.Cells[rowSum, 2] = "合计";
  108. // xSt.get_Range(excel.Cells[rowSum, 2], excel.Cells[rowSum, 2]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
  109. // //设置选中的部分的颜色
  110. // xSt.get_Range(excel.Cells[rowSum, colSum], excel.Cells[rowSum, colIndex]).Select();
  111. // //xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex =Assistant.GetConfigInt("ColorIndex");// 1;//设置为浅黄色,共计有56种
  112. // //取得整个报表的标题
  113. // excel.Cells[2, 2] = strTitle;
  114. // //设置整个报表的标题格式
  115. // xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, 2]).Font.Bold = true;
  116. // xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, 2]).Font.Size = 22;
  117. // //设置报表表格为最适应宽度
  118. // xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, colIndex]).Select();
  119. // xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, colIndex]).Columns.AutoFit();
  120. // //设置整个报表的标题为跨列居中
  121. // xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, colIndex]).Select();
  122. // xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, colIndex]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenterAcrossSelection;
  123. // //绘制边框
  124. // xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, colIndex]).Borders.LineStyle = 1;
  125. // xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, 2]).Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlThick;//设置左边线加粗
  126. // xSt.get_Range(excel.Cells[4, 2], excel.Cells[4, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = Excel.XlBorderWeight.xlThick;//设置上边线加粗
  127. // xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[rowSum, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = Excel.XlBorderWeight.xlThick;//设置右边线加粗
  128. // xSt.get_Range(excel.Cells[rowSum, 2], excel.Cells[rowSum, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = Excel.XlBorderWeight.xlThick;//设置下边线加粗
  129. // afterTime = DateTime.Now;
  130. // //显示效果
  131. // //excel.Visible=true;
  132. // //excel.Sheets[0] = "sss";
  133. // ClearFile(FilePath);
  134. // string filename = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xls";
  135. // excel.ActiveWorkbook.SaveAs(FilePath + filename, Excel.XlFileFormat.xlExcel9795, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
  136. // //wkbNew.SaveAs strBookName;
  137. // //excel.Save(strExcelFileName);
  138. // #region 结束Excel进程
  139. // //需要对Excel的DCOM对象进行配置:dcomcnfg
  140. // //excel.Quit();
  141. // //excel=null;
  142. // xBk.Close(null, null, null);
  143. // excel.Workbooks.Close();
  144. // excel.Quit();
  145. // //注意:这里用到的所有Excel对象都要执行这个操作,否则结束不了Excel进程
  146. // // if(rng != null)
  147. // // {
  148. // // System.Runtime.InteropServices.Marshal.ReleaseComObject(rng);
  149. // // rng = null;
  150. // // }
  151. // // if(tb != null)
  152. // // {
  153. // // System.Runtime.InteropServices.Marshal.ReleaseComObject(tb);
  154. // // tb = null;
  155. // // }
  156. // if (xSt != null)
  157. // {
  158. // System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
  159. // xSt = null;
  160. // }
  161. // if (xBk != null)
  162. // {
  163. // System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
  164. // xBk = null;
  165. // }
  166. // if (excel != null)
  167. // {
  168. // System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
  169. // excel = null;
  170. // }
  171. // GC.Collect();//垃圾回收
  172. // #endregion
  173. // return filename;
  174. //}
  175. #endregion
  176. #region Kill Excel进程
  177. /// <summary>
  178. /// 结束Excel进程
  179. /// </summary>
  180. public void KillExcelProcess()
  181. {
  182. Process[] myProcesses;
  183. DateTime startTime;
  184. myProcesses = Process.GetProcessesByName("Excel");
  185. //得不到Excel进程ID,暂时只能判断进程启动时间
  186. foreach (Process myProcess in myProcesses)
  187. {
  188. startTime = myProcess.StartTime;
  189. if (startTime > beforeTime && startTime < afterTime)
  190. {
  191. myProcess.Kill();
  192. }
  193. }
  194. }
  195. #endregion
  196. #endregion
  197. #region 将DataTable的数据导出显示为报表(不使用Excel对象,使用COM.Excel)
  198. #region 使用示例
  199. /*使用示例:
  200. * DataSet ds=(DataSet)Session["AdBrowseHitDayList"];
  201. string ExcelFolder=Assistant.GetConfigString("ExcelFolder");
  202. string FilePath=Server.MapPath(".")+"\\"+ExcelFolder+"\\";
  203. //生成列的中文对应表
  204. Hashtable nameList = new Hashtable();
  205. nameList.Add("ADID", "广告编码");
  206. nameList.Add("ADName", "广告名称");
  207. nameList.Add("year", "年");
  208. nameList.Add("month", "月");
  209. nameList.Add("browsum", "显示数");
  210. nameList.Add("hitsum", "点击数");
  211. nameList.Add("BrowsinglIP", "独立IP显示");
  212. nameList.Add("HitsinglIP", "独立IP点击");
  213. //利用excel对象
  214. DataToExcel dte=new DataToExcel();
  215. string filename="";
  216. try
  217. {
  218. if(ds.Tables[0].Rows.Count>0)
  219. {
  220. filename=dte.DataExcel(ds.Tables[0],"标题",FilePath,nameList);
  221. }
  222. }
  223. catch
  224. {
  225. //dte.KillExcelProcess();
  226. }
  227. if(filename!="")
  228. {
  229. Response.Redirect(ExcelFolder+"\\"+filename,true);
  230. }
  231. *
  232. * */
  233. #endregion
  234. /// <summary>
  235. /// 将DataTable的数据导出显示为报表(不使用Excel对象)
  236. /// </summary>
  237. /// <param name="dt">数据DataTable</param>
  238. /// <param name="strTitle">标题</param>
  239. /// <param name="FilePath">生成文件的路径</param>
  240. /// <param name="nameList"></param>
  241. /// <returns></returns>
  242. //public string DataExcel(System.Data.DataTable dt, string strTitle, string FilePath, Hashtable nameList)
  243. //{
  244. // COM.Excel.cExcelFile excel = new COM.Excel.cExcelFile();
  245. // ClearFile(FilePath);
  246. // string filename = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xls";
  247. // excel.CreateFile(FilePath + filename);
  248. // excel.PrintGridLines = false;
  249. // COM.Excel.cExcelFile.MarginTypes mt1 = COM.Excel.cExcelFile.MarginTypes.xlsTopMargin;
  250. // COM.Excel.cExcelFile.MarginTypes mt2 = COM.Excel.cExcelFile.MarginTypes.xlsLeftMargin;
  251. // COM.Excel.cExcelFile.MarginTypes mt3 = COM.Excel.cExcelFile.MarginTypes.xlsRightMargin;
  252. // COM.Excel.cExcelFile.MarginTypes mt4 = COM.Excel.cExcelFile.MarginTypes.xlsBottomMargin;
  253. // double height = 1.5;
  254. // excel.SetMargin(ref mt1, ref height);
  255. // excel.SetMargin(ref mt2, ref height);
  256. // excel.SetMargin(ref mt3, ref height);
  257. // excel.SetMargin(ref mt4, ref height);
  258. // COM.Excel.cExcelFile.FontFormatting ff = COM.Excel.cExcelFile.FontFormatting.xlsNoFormat;
  259. // string font = "宋体";
  260. // short fontsize = 9;
  261. // excel.SetFont(ref font, ref fontsize, ref ff);
  262. // byte b1 = 1,
  263. // b2 = 12;
  264. // short s3 = 12;
  265. // excel.SetColumnWidth(ref b1, ref b2, ref s3);
  266. // string header = "页眉";
  267. // string footer = "页脚";
  268. // excel.SetHeader(ref header);
  269. // excel.SetFooter(ref footer);
  270. // COM.Excel.cExcelFile.ValueTypes vt = COM.Excel.cExcelFile.ValueTypes.xlsText;
  271. // COM.Excel.cExcelFile.CellFont cf = COM.Excel.cExcelFile.CellFont.xlsFont0;
  272. // COM.Excel.cExcelFile.CellAlignment ca = COM.Excel.cExcelFile.CellAlignment.xlsCentreAlign;
  273. // COM.Excel.cExcelFile.CellHiddenLocked chl = COM.Excel.cExcelFile.CellHiddenLocked.xlsNormal;
  274. // // 报表标题
  275. // int cellformat = 1;
  276. // // int rowindex = 1,colindex = 3;
  277. // // object title = (object)strTitle;
  278. // // excel.WriteValue(ref vt, ref cf, ref ca, ref chl,ref rowindex,ref colindex,ref title,ref cellformat);
  279. // int rowIndex = 1;//起始行
  280. // int colIndex = 0;
  281. // //取得列标题
  282. // foreach (DataColumn colhead in dt.Columns)
  283. // {
  284. // colIndex++;
  285. // string name = colhead.ColumnName.Trim();
  286. // object namestr = (object)name;
  287. // IDictionaryEnumerator Enum = nameList.GetEnumerator();
  288. // while (Enum.MoveNext())
  289. // {
  290. // if (Enum.Key.ToString().Trim() == name)
  291. // {
  292. // namestr = Enum.Value;
  293. // }
  294. // }
  295. // excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref namestr, ref cellformat);
  296. // }
  297. // //取得表格中的数据
  298. // foreach (DataRow row in dt.Rows)
  299. // {
  300. // rowIndex++;
  301. // colIndex = 0;
  302. // foreach (DataColumn col in dt.Columns)
  303. // {
  304. // colIndex++;
  305. // if (col.DataType == System.Type.GetType("System.DateTime"))
  306. // {
  307. // object str = (object)(Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd"); ;
  308. // excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref str, ref cellformat);
  309. // }
  310. // else
  311. // {
  312. // object str = (object)row[col.ColumnName].ToString();
  313. // excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref str, ref cellformat);
  314. // }
  315. // }
  316. // }
  317. // int ret = excel.CloseFile();
  318. // // if(ret!=0)
  319. // // {
  320. // // //MessageBox.Show(this,"Error!");
  321. // // }
  322. // // else
  323. // // {
  324. // // //MessageBox.Show(this,"请打开文件c:\\test.xls!");
  325. // // }
  326. // return filename;
  327. //}
  328. #endregion
  329. #region 清理过时的Excel文件
  330. private void ClearFile(string FilePath)
  331. {
  332. String[] Files = System.IO.Directory.GetFiles(FilePath);
  333. if (Files.Length > 10)
  334. {
  335. for (int i = 0; i < 10; i++)
  336. {
  337. try
  338. {
  339. System.IO.File.Delete(Files[i]);
  340. }
  341. catch
  342. {
  343. }
  344. }
  345. }
  346. }
  347. #endregion
  348. }
  349. }