ExcelLayer.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /*******************************************************************************
  2. * Copyright(c) 2014 dongke All rights reserved. / Confidential
  3. * 类的信息:
  4. * 1.程序名称:ExcelLayer.cs
  5. * 2.功能描述:类文件
  6. * 编辑履历:
  7. * 作者 日期 版本 修改内容
  8. * 陈冰 2014/9/22 1.00 新建
  9. *******************************************************************************/
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Web;
  14. using System.Data;
  15. using System.Data.OleDb;
  16. using System.Windows.Forms;
  17. using Dongke.IBOSS.PRD.Basics.BaseResources;
  18. using System.IO;
  19. using System.Reflection;
  20. namespace Dongke.IBOSS.PRD.Basics.Library
  21. {
  22. public class ExcelLayer
  23. {
  24. /// <summary>
  25. /// Retireves the data from Excel Sheet to a DataTable.
  26. /// </summary>
  27. /// <param name="FileName">File Name along with path from the root folder.</param>
  28. /// <param name="TableName">Name of the Table of the Excel Sheet. Sheet1$ if no table.</param>
  29. /// <returns></returns>
  30. public static DataTable GetDataTable(string FileName, string TableName, int v)
  31. {
  32. OleDbConnection objConn = null;
  33. try
  34. {
  35. string strPath = FileName;
  36. DataSet ds = new DataSet();
  37. string sConnectionString = null;
  38. if (v == 0)
  39. {
  40. sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " + "Data Source=" + strPath + "; " + "Extended Properties='Excel 8.0; HDR=Yes; IMEX=1;';";
  41. }
  42. else if (v == 1)
  43. {
  44. sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; " + "Data Source=" + strPath + "; " + "Extended Properties='Excel 12.0; HDR=Yes; IMEX=1;';";
  45. }
  46. objConn = new OleDbConnection(sConnectionString);
  47. objConn.Open();
  48. TableName += "$";
  49. string strTableName = TableName;
  50. try
  51. {
  52. DataTable sheetNames = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
  53. int index = 0;
  54. foreach (DataRow drTableName in sheetNames.Rows)
  55. {
  56. string tName = drTableName["TABLE_NAME"].ToString();
  57. if (index == 0)
  58. {
  59. strTableName = tName;
  60. }
  61. index++;
  62. if (tName == TableName)
  63. {
  64. strTableName = TableName;
  65. break;
  66. }
  67. }
  68. }
  69. catch (Exception ex)
  70. {
  71. OutputLog.Trace(LogPriority.Error, "ExcelLayer",
  72. "GetDataTable(FileName, TableName) GetSheetNames", ex.ToString());
  73. }
  74. using (OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + strTableName + "]", objConn))
  75. {
  76. OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
  77. objAdapter1.SelectCommand = objCmdSelect;
  78. objAdapter1.Fill(ds);
  79. objConn.Close();
  80. objConn = null;
  81. return ds.Tables[0];
  82. }
  83. }
  84. catch (Exception ex)
  85. {
  86. if (objConn != null)
  87. {
  88. objConn.Close();
  89. objConn = null;
  90. }
  91. //throw ex;
  92. //Log your exception here.//
  93. OutputLog.Trace(LogPriority.Error, "ExcelLayer",
  94. "GetDataTable(FileName, TableName)", ex.ToString());
  95. return (DataTable)null;
  96. }
  97. }
  98. /// <summary>
  99. /// Retireves the data from Excel Sheet to a DataTable.
  100. /// </summary>
  101. /// <param name="FileName">File Name along with path from the root folder.</param>
  102. /// <param name="TableName">Name of the Table of the Excel Sheet. Sheet1$ if no table.</param>
  103. /// <returns></returns>
  104. public static DataTable GetDataTable(string FileName, int v)
  105. {
  106. OleDbConnection objConn = null;
  107. try
  108. {
  109. string strPath = FileName;
  110. DataSet ds = new DataSet();
  111. string sConnectionString = null;
  112. // Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;
  113. if (v == 0)
  114. {
  115. sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " + "Data Source=" + strPath + "; " + "Extended Properties='Excel 8.0; HDR=Yes; IMEX=1;';";
  116. }
  117. else if (v == 1)
  118. {
  119. sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; " + "Data Source=" + strPath + "; " + "Extended Properties='Excel 12.0; HDR=Yes; IMEX=1;';";
  120. }
  121. objConn = new OleDbConnection(sConnectionString);
  122. objConn.Open();
  123. string strTableName = string.Empty;
  124. DataTable sheetNames = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
  125. foreach (DataRow drTableName in sheetNames.Rows)
  126. {
  127. strTableName = drTableName["TABLE_NAME"].ToString();
  128. if (!string.IsNullOrEmpty(strTableName))
  129. {
  130. break;
  131. }
  132. }
  133. using (OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + strTableName + "]", objConn))
  134. {
  135. OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
  136. objAdapter1.SelectCommand = objCmdSelect;
  137. objAdapter1.Fill(ds);
  138. objConn.Close();
  139. return ds.Tables[0];
  140. }
  141. }
  142. catch (Exception ex)
  143. {
  144. if (objConn != null)
  145. {
  146. objConn.Close();
  147. objConn = null;
  148. }
  149. //throw ex;
  150. //Log your exception here.//
  151. OutputLog.Trace(LogPriority.Error, "ExcelLayer",
  152. "GetDataTable(FileName)", ex.ToString());
  153. return (DataTable)null;
  154. }
  155. }
  156. public static void ExportExcel(DataTable exportDataTable, string text, string tableName, string fileNameString)
  157. {
  158. Interop.Excel.Application oXL = null;
  159. Interop.Excel._Workbook oWB = null;
  160. Interop.Excel._Worksheet oSheet = null;
  161. Interop.Excel.Range oRng = null;
  162. Interop.Excel.Range range = null;
  163. try
  164. {
  165. if (exportDataTable.Rows.Count == 0)
  166. {
  167. MessageBox.Show(string.Format(Messages.MSG_CMN_W007,
  168. "没有导出的数据"),
  169. text,
  170. MessageBoxButtons.OK,
  171. MessageBoxIcon.Warning);
  172. return;
  173. }
  174. SaveFileDialog dialog = new SaveFileDialog();
  175. if (string.IsNullOrEmpty(fileNameString.Trim()))
  176. {
  177. return;
  178. }
  179. int rowCount = exportDataTable.Rows.Count;
  180. int columnCount = exportDataTable.Columns.Count;
  181. // 行数不能大于65536
  182. if (rowCount > 65536)
  183. {
  184. MessageBox.Show(string.Format(Messages.MSG_CMN_W007,
  185. "导出数据太多(最多不能超过65536条)"),
  186. text,
  187. MessageBoxButtons.OK,
  188. MessageBoxIcon.Warning);
  189. return;
  190. }
  191. // 列数不能大于255
  192. if (columnCount > 255)
  193. {
  194. MessageBox.Show(string.Format(Messages.MSG_CMN_W007,
  195. "导出数据列数太多(最多不能超过255列)"),
  196. text,
  197. MessageBoxButtons.OK,
  198. MessageBoxIcon.Warning);
  199. return;
  200. }
  201. // 验证以fileNameString命名的文件是否存在,如果存在提示
  202. FileInfo file = new FileInfo(fileNameString);
  203. if (file.Exists)
  204. {
  205. MessageBox.Show(string.Format(Messages.MSG_CMN_W007,
  206. "文件名" + fileNameString + "已存在"),
  207. text,
  208. MessageBoxButtons.OK,
  209. MessageBoxIcon.Warning);
  210. return;
  211. }
  212. oXL = new Interop.Excel.Application();
  213. if (oXL == null)
  214. {
  215. MessageBox.Show(string.Format(Messages.MSG_CMN_W007,
  216. "请确保您的电脑已经安装Excel"),
  217. text,
  218. MessageBoxButtons.OK,
  219. MessageBoxIcon.Warning);
  220. return;
  221. }
  222. oXL.UserControl = false;
  223. oXL.Visible = false;
  224. //创建一个新的workboot
  225. oWB = (Interop.Excel._Workbook)(oXL.Workbooks.Add(true));
  226. oSheet = (Interop.Excel._Worksheet)oWB.ActiveSheet;
  227. if (oSheet == null)
  228. {
  229. MessageBox.Show(string.Format(Messages.MSG_CMN_W007,
  230. "请确保您的电脑已经安装Excel"),
  231. text,
  232. MessageBoxButtons.OK,
  233. MessageBoxIcon.Warning);
  234. return;
  235. }
  236. oSheet.Name = tableName;
  237. List<string> nodeList = new List<string>();
  238. int maxColumnsCount = 0;
  239. int j = 1;
  240. for (int i = 0; i < exportDataTable.Columns.Count; i++)
  241. {
  242. //TreeNode node = (TreeNode)exportDataTable.ColumnList[i];
  243. if (exportDataTable.Columns[i].DataType == typeof(string))
  244. {
  245. //设置excel文件中为文本型
  246. range = oSheet.get_Range(oSheet.Cells[1, maxColumnsCount + 1],
  247. oSheet.Cells[exportDataTable.Rows.Count + 3, maxColumnsCount + 1]);
  248. range.NumberFormat = "@";//格式设置为文本
  249. }
  250. //string[] fullpath = node.FullPath.Split('\\');
  251. // 获取对于excel中列的列号
  252. string excelcolumn = GetCharByInt(maxColumnsCount + 1);
  253. oSheet.Cells[j, maxColumnsCount + 1] = exportDataTable.Columns[i].ColumnName;
  254. //oSheet.get_Range(excelcolumn + j, excelcolumn + (columnDeep - j + 1)).MergeCells = true;
  255. //oSheet.get_Range(excelcolumn + j, excelcolumn + (columnDeep - j + 1)).HorizontalAlignment
  256. // = Interop.Excel.Constants.xlCenter;//居中
  257. maxColumnsCount++;
  258. }
  259. // 控制表头的格式信息
  260. for (int i = 1; i < 4; i++)
  261. {
  262. oRng = oSheet.get_Range("A" + i, GetCharByInt(maxColumnsCount) + i);
  263. oRng.EntireColumn.AutoFit();
  264. oSheet.get_Range("A" + i, GetCharByInt(maxColumnsCount) + i).Borders.Weight = Interop.Excel.XlBorderWeight.xlThin;
  265. }
  266. j = 4;// 从第四行填数据
  267. string maxColumnStr = GetCharByInt(maxColumnsCount) + j;
  268. for (int x = 0; x < exportDataTable.Rows.Count; x++)
  269. {
  270. //范围内单元格自动适应文字的长短
  271. oRng = oSheet.get_Range("A" + j, maxColumnStr);
  272. oRng.EntireColumn.AutoFit();
  273. oSheet.get_Range("A" + j, maxColumnStr).Borders.Weight = Interop.Excel.XlBorderWeight.xlThin;
  274. int b = 0;
  275. for (int i = 0; i < exportDataTable.Columns.Count; i++)
  276. {
  277. oSheet.Cells[j, b + 1] = exportDataTable.Rows[x][i];
  278. b++;
  279. }
  280. j++;
  281. }
  282. object missing = System.Reflection.Missing.Value;
  283. oSheet.Protect(missing, missing, false, missing, true, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, false); //生成模板
  284. //oSheet.PageSetup.Orientation = Interop.Excel.XlPageOrientation.xlPortrait; //设置为纵向打印
  285. oSheet.PageSetup.Orientation = Interop.Excel.XlPageOrientation.xlLandscape; //设置为横向打印
  286. oSheet.PageSetup.PaperSize = Interop.Excel.XlPaperSize.xlPaperA4; //设置打印字为A4纸张
  287. // 其中 56 为 2003兼容格式
  288. oXL.ActiveWorkbook.SaveAs(fileNameString, 56, Missing.Value, Missing.Value, Missing.Value,
  289. Missing.Value, Interop.Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value,
  290. Missing.Value, Missing.Value, Missing.Value, Missing.Value);
  291. }
  292. catch (Exception)
  293. {
  294. MessageBox.Show("导出失败",
  295. text,
  296. MessageBoxButtons.OK,
  297. MessageBoxIcon.Error);
  298. return;
  299. }
  300. finally
  301. {
  302. // 关闭Excel应用
  303. if (oXL != null)
  304. {
  305. oXL.ActiveWorkbook.Close(Missing.Value, Missing.Value, Missing.Value);
  306. if (oXL.Workbooks != null)
  307. {
  308. oXL.Workbooks.Close();
  309. }
  310. oXL.Quit();//Excel正常退出
  311. System.Runtime.InteropServices.Marshal.ReleaseComObject((object)oXL);
  312. System.GC.Collect();
  313. MessageBox.Show("导出成功", text,
  314. MessageBoxButtons.OK,
  315. MessageBoxIcon.Information);
  316. }
  317. }
  318. }
  319. /// <summary>
  320. /// 由Int型获取相应的Char字符串(只支持2位,导出EXCEL时使用)
  321. /// </summary>
  322. /// <returns></returns>
  323. private static string GetCharByInt(int charint)
  324. {
  325. try
  326. {
  327. int a = charint / 26;
  328. int b = charint % 26;
  329. if (charint % 26 == 0)
  330. {
  331. a = a - 1;
  332. b = 26;
  333. }
  334. string aa = "";
  335. string bb = "";
  336. if (a != 0)
  337. {
  338. aa = (char)(a + 64) + "";
  339. }
  340. if (b != 0)
  341. {
  342. bb = (char)(b + 64) + "";
  343. }
  344. return aa + "" + bb;
  345. }
  346. catch (Exception ex)
  347. {
  348. throw ex;
  349. }
  350. }
  351. }
  352. }