ExcelHelper.cs 3.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Data.OleDb;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Windows.Forms;
  9. using DotNettyFrom.util;
  10. namespace DotNettyFrom.excel
  11. {
  12. public class ExcelHelper
  13. {
  14. private string excelConn = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source = ";
  15. private RichTextBox richTextBox;
  16. private List<WvBean> excelList = new List<WvBean>();
  17. public ExcelHelper(string excelPath, RichTextBox richTextBox)
  18. {
  19. this.richTextBox = richTextBox;
  20. excelConn += excelPath + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";
  21. }
  22. public List<WvBean> GetExcelList()
  23. {
  24. return excelList;
  25. }
  26. public ExcelHelper LoadExcelFile()
  27. {
  28. using (OleDbConnection conn = new OleDbConnection(excelConn))
  29. {
  30. conn.Open();
  31. DataSet dataSet = new DataSet();
  32. try
  33. {
  34. OleDbDataAdapter odda = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", conn);
  35. odda.Fill(dataSet, "Sheet1$");
  36. if (dataSet.Tables.Count > 0)
  37. {
  38. DataTable dt = dataSet.Tables[0];
  39. int hang = dt.Rows.Count;
  40. excelList.Clear();
  41. for (int i = 1; i < hang; i++)
  42. {
  43. WvBean wb = null;
  44. try
  45. {
  46. int myIndex = int.Parse(dt.Rows[i][0] + "");
  47. string myId = CmdUtil.FrontWithZero(CmdUtil.Dec2Hex(myIndex), 4);
  48. string idInfo = dt.Rows[i][1].ToString().Trim();
  49. string len = dt.Rows[i][2].ToString().Trim();
  50. string mode = dt.Rows[i][3].ToString().Trim();
  51. string desp = dt.Rows[i][4].ToString().Trim();
  52. string defaultValue = dt.Rows[i][5].ToString().Trim();
  53. string remark = dt.Rows[i][6].ToString().Trim();
  54. if (len.Equals("") || mode.Equals("") || defaultValue.Equals(""))
  55. {
  56. richTextBox.Text += "第" + i + "行;长度,模式,默认值不能为空\n";
  57. continue;
  58. }
  59. wb = new WvBean();
  60. wb.index = myIndex;
  61. wb.myId = myId;
  62. wb.idInfo = idInfo;
  63. wb.len = len;
  64. wb.mode = mode;
  65. wb.desp = desp;
  66. wb.defalutValue = defaultValue;
  67. wb.userValue = defaultValue;
  68. wb.remark = remark;
  69. excelList.Add(wb);
  70. }
  71. catch (Exception exception)
  72. {
  73. richTextBox.Text += "第" + i + "行;" + exception.Message + "\n";
  74. Console.WriteLine(exception);
  75. }
  76. }
  77. }
  78. }
  79. catch (Exception exception)
  80. {
  81. Console.WriteLine(exception.Message);
  82. richTextBox.Text = "请确定Excel表名为\"Sheet1\"\n" + exception.Message + "\n";
  83. }
  84. }
  85. return this;
  86. }
  87. }
  88. }