using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using DotNettyFrom.util; namespace DotNettyFrom.excel { public class ExcelHelper { private string excelConn = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source = "; private RichTextBox richTextBox; private List excelList = new List(); public ExcelHelper(string excelPath, RichTextBox richTextBox) { this.richTextBox = richTextBox; excelConn += excelPath + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'"; } public List GetExcelList() { return excelList; } public ExcelHelper LoadExcelFile() { using (OleDbConnection conn = new OleDbConnection(excelConn)) { conn.Open(); DataSet dataSet = new DataSet(); try { OleDbDataAdapter odda = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", conn); odda.Fill(dataSet, "Sheet1$"); if (dataSet.Tables.Count > 0) { DataTable dt = dataSet.Tables[0]; int hang = dt.Rows.Count; excelList.Clear(); for (int i = 1; i < hang; i++) { WvBean wb = null; try { int myIndex = int.Parse(dt.Rows[i][0] + ""); string myId = CmdUtil.FrontWithZero(CmdUtil.Dec2Hex(myIndex), 4); string idInfo = dt.Rows[i][1].ToString().Trim(); string len = dt.Rows[i][2].ToString().Trim(); string mode = dt.Rows[i][3].ToString().Trim(); string desp = dt.Rows[i][4].ToString().Trim(); string defaultValue = dt.Rows[i][5].ToString().Trim(); string remark = dt.Rows[i][6].ToString().Trim(); if (len.Equals("") || mode.Equals("") || defaultValue.Equals("")) { richTextBox.Text += "第" + i + "行;长度,模式,默认值不能为空\n"; continue; } wb = new WvBean(); wb.index = myIndex; wb.myId = myId; wb.idInfo = idInfo; wb.len = len; wb.mode = mode; wb.desp = desp; wb.defalutValue = defaultValue; wb.userValue = defaultValue; wb.remark = remark; excelList.Add(wb); } catch (Exception exception) { richTextBox.Text += "第" + i + "行;" + exception.Message + "\n"; Console.WriteLine(exception); } } } } catch (Exception exception) { Console.WriteLine(exception.Message); richTextBox.Text = "请确定Excel表名为\"Sheet1\"\n" + exception.Message + "\n"; } } return this; } } }