C#操作Excel資料增刪改查樣本

來源:互聯網
上載者:User
C#操作Excel資料增刪改查。

首先建立ExcelDB.xlsx檔案,並添加兩張工作表。

工作表1:

UserInfo表,欄位:UserId、UserName、Age、Address、CreateTime。

工作表2:

Order表,欄位:OrderNo、ProductName、Quantity、Money、SaleDate。

1、建立ExcelHelper.cs類,Excel檔案處理類

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.OleDb; using System.Data; namespace MyStudy.DAL { /// <summary> /// Excel檔案處理類 /// </summary> public class ExcelHelper { private static string fileName = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"/ExcelFile/ExcelDB.xlsx"; private static OleDbConnection connection; public static OleDbConnection Connection { get { string connectionString = ""; string fileType = System.IO.Path.GetExtension(fileName); if (string.IsNullOrEmpty(fileType)) return null; if (fileType == ".xls") { connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=2\""; } else { connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=2\""; } if (connection == null) { connection = new OleDbConnection(connectionString); connection.Open(); } else if (connection.State == System.Data.ConnectionState.Closed) { connection.Open(); } else if (connection.State == System.Data.ConnectionState.Broken) { connection.Close(); connection.Open(); } return connection; } } /// <summary> /// 執行無參數的SQL語句 /// </summary> /// <param name="sql">SQL語句</param> /// <returns>返回受SQL語句影響的行數</returns> public static int ExecuteCommand(string sql) { OleDbCommand cmd = new OleDbCommand(sql, Connection); int result = cmd.ExecuteNonQuery(); connection.Close(); return result; } /// <summary> /// 執行有參數的SQL語句 /// </summary> /// <param name="sql">SQL語句</param> /// <param name="values">參數集合</param> /// <returns>返回受SQL語句影響的行數</returns> public static int ExecuteCommand(string sql, params OleDbParameter[] values) { OleDbCommand cmd = new OleDbCommand(sql, Connection); cmd.Parameters.AddRange(values); int result = cmd.ExecuteNonQuery(); connection.Close(); return result; } /// <summary> /// 返回單個值無參數的SQL語句 /// </summary> /// <param name="sql">SQL語句</param> /// <returns>返回受SQL語句查詢的行數</returns> public static int GetScalar(string sql) { OleDbCommand cmd = new OleDbCommand(sql, Connection); int result = Convert.ToInt32(cmd.ExecuteScalar()); connection.Close(); return result; } /// <summary> /// 返回單個值有參數的SQL語句 /// </summary> /// <param name="sql">SQL語句</param> /// <param name="parameters">參數集合</param> /// <returns>返回受SQL語句查詢的行數</returns> public static int GetScalar(string sql, params OleDbParameter[] parameters) { OleDbCommand cmd = new OleDbCommand(sql, Connection); cmd.Parameters.AddRange(parameters); int result = Convert.ToInt32(cmd.ExecuteScalar()); connection.Close(); return result; } /// <summary> /// 執行查詢無參數SQL語句 /// </summary> /// <param name="sql">SQL語句</param> /// <returns>返回資料集</returns> public static DataSet GetReader(string sql) { OleDbDataAdapter da = new OleDbDataAdapter(sql, Connection); DataSet ds = new DataSet(); da.Fill(ds, "UserInfo"); connection.Close(); return ds; } /// <summary> /// 執行查詢有參數SQL語句 /// </summary> /// <param name="sql">SQL語句</param> /// <param name="parameters">參數集合</param> /// <returns>返回資料集</returns> public static DataSet GetReader(string sql, params OleDbParameter[] parameters) { OleDbDataAdapter da = new OleDbDataAdapter(sql, Connection); da.SelectCommand.Parameters.AddRange(parameters); DataSet ds = new DataSet(); da.Fill(ds); connection.Close(); return ds; } } }

2、 建立實體類

2.1 建立UserInfo.cs類,使用者資訊實體類。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace MyStudy.Model { /// <summary> /// 使用者資訊實體類 /// </summary> public class UserInfo { public int UserId { get; set; } public string UserName { get; set; } public int? Age { get; set; } public string Address { get; set; } public DateTime? CreateTime { get; set; } /// <summary> /// 將DataTable轉換成List資料 /// </summary> public static List<UserInfo> ToList(DataSet dataSet) { List<UserInfo> userList = new List<UserInfo>(); if (dataSet != null && dataSet.Tables.Count > 0) { foreach (DataRow row in dataSet.Tables[0].Rows) { UserInfo user = new UserInfo(); if (dataSet.Tables[0].Columns.Contains("UserId") && !Convert.IsDBNull(row["UserId"])) user.UserId = Convert.ToInt32(row["UserId"]); if (dataSet.Tables[0].Columns.Contains("UserName") && !Convert.IsDBNull(row["UserName"])) user.UserName = (string)row["UserName"]; if (dataSet.Tables[0].Columns.Contains("Age") && !Convert.IsDBNull(row["Age"])) user.Age = Convert.ToInt32(row["Age"]); if (dataSet.Tables[0].Columns.Contains("Address") && !Convert.IsDBNull(row["Address"])) user.Address = (string)row["Address"]; if (dataSet.Tables[0].Columns.Contains("CreateTime") && !Convert.IsDBNull(row["CreateTime"])) user.CreateTime = Convert.ToDateTime(row["CreateTime"]); userList.Add(user); } } return userList; } } }

2.2 建立Order.cs類,訂單實體類。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace MyStudy.Model { /// <summary> /// 訂單實體類 /// </summary> public class Order { public string OrderNo { get; set; } public string ProductName { get; set; } public int? Quantity { get; set; } public decimal? Money { get; set; } public DateTime? SaleDate { get; set; } /// <summary> /// 將DataTable轉換成List資料 /// </summary> public static List<Order> ToList(DataSet dataSet) { List<Order> orderList = new List<Order>(); if (dataSet != null && dataSet.Tables.Count > 0) { foreach (DataRow row in dataSet.Tables[0].Rows) { Order order = new Order(); if (dataSet.Tables[0].Columns.Contains("OrderNo") && !Convert.IsDBNull(row["OrderNo"])) order.OrderNo = (string)row["OrderNo"]; if (dataSet.Tables[0].Columns.Contains("ProductName") && !Convert.IsDBNull(row["ProductName"])) order.ProductName = (string)row["ProductName"]; if (dataSet.Tables[0].Columns.Contains("Quantity") && !Convert.IsDBNull(row["Quantity"])) order.Quantity = Convert.ToInt32(row["Quantity"]); if (dataSet.Tables[0].Columns.Contains("Money") && !Convert.IsDBNull(row["Money"])) order.Money = Convert.ToDecimal(row["Money"]); if (dataSet.Tables[0].Columns.Contains("SaleDate") && !Convert.IsDBNull(row["SaleDate"])) order.SaleDate = Convert.ToDateTime(row["SaleDate"]); orderList.Add(order); } } return orderList; } } }

3、建立商務邏輯類

3.1 建立UserInfoBLL.cs類,使用者資訊業務類。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using MyStudy.Model; using MyStudy.DAL; using System.Data.OleDb; namespace MyStudy.BLL { /// <summary> /// 使用者資訊業務類 /// </summary> public class UserInfoBLL { /// <summary> /// 查詢使用者列表 /// </summary> public List<UserInfo> GetUserList() { List<UserInfo> userList = new List<UserInfo>(); string sql = "SELECT * FROM [UserInfo$]"; DataSet dateSet = ExcelHelper.GetReader(sql); userList = UserInfo.ToList(dateSet); return userList; } /// <summary> /// 擷取使用者總數 /// </summary> public int GetUserCount() { int result = 0; string sql = "SELECT COUNT(*) FROM [UserInfo$]"; result = ExcelHelper.GetScalar(sql); return result; } /// <summary> /// 新增使用者資訊 /// </summary> public int AddUserInfo(UserInfo param) { int result = 0; string sql = "INSERT INTO [UserInfo$](UserId,UserName,Age,Address,CreateTime) VALUES(@UserId,@UserName,@Age,@Address,@CreateTime)"; OleDbParameter[] oleDbParam = new OleDbParameter[] { new OleDbParameter("@UserId", param.UserId), new OleDbParameter("@UserName", param.UserName), new OleDbParameter("@Age", param.Age), new OleDbParameter("@Address",param.Address), new OleDbParameter("@CreateTime",param.CreateTime) }; result = ExcelHelper.ExecuteCommand(sql, oleDbParam); return result; } /// <summary> /// 修改使用者資訊 /// </summary> public int UpdateUserInfo(UserInfo param) { int result = 0; if (param.UserId > 0) { string sql = "UPDATE [UserInfo$] SET UserName=@UserName,Age=@Age,Address=@Address WHERE UserId=@UserId"; OleDbParameter[] sqlParam = new OleDbParameter[] { new OleDbParameter("@UserId",param.UserId), new OleDbParameter("@UserName", param.UserName), new OleDbParameter("@Age", param.Age), new OleDbParameter("@Address",param.Address) }; result = ExcelHelper.ExecuteCommand(sql, sqlParam); } return result; } /// <summary> /// 刪除使用者資訊 /// </summary> public int DeleteUserInfo(UserInfo param) { int result = 0; if (param.UserId > 0) { string sql = "DELETE [UserInfo$] WHERE UserId=@UserId"; OleDbParameter[] sqlParam = new OleDbParameter[] { new OleDbParameter("@UserId",param.UserId), }; result = ExcelHelper.ExecuteCommand(sql, sqlParam); } return result; } } }

3.2 建立OrderBLL.cs類,訂單業務類

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using MyStudy.Model; using MyStudy.DAL; using System.Data.OleDb; namespace MyStudy.BLL { /// <summary> /// 訂單業務類 /// </summary> public class OrderBLL { /// <summary> /// 查詢訂單列表 /// </summary> public List<Order> GetOrderList() { List<Order> orderList = new List<Order>(); string sql = "SELECT * FROM [Order$]"; DataSet dateSet = ExcelHelper.GetReader(sql); orderList = Order.ToList(dateSet); return orderList; } /// <summary> /// 擷取訂單總數 /// </summary> public int GetOrderCount() { int result = 0; string sql = "SELECT COUNT(*) FROM [Order$]"; result = ExcelHelper.GetScalar(sql); return result; } /// <summary> /// 新增訂單 /// </summary> public int AddOrder(Order param) { int result = 0; string sql = "INSERT INTO [Order$](OrderNo,ProductName,Quantity,Money,SaleDate) VALUES(@OrderNo,@ProductName,@Quantity,@Money,@SaleDate)"; OleDbParameter[] oleDbParam = new OleDbParameter[] { new OleDbParameter("@OrderNo", param.OrderNo), new OleDbParameter("@ProductName", param.ProductName), new OleDbParameter("@Quantity", param.Quantity), new OleDbParameter("@Money",param.Money), new OleDbParameter("@SaleDate",param.SaleDate) }; result = ExcelHelper.ExecuteCommand(sql, oleDbParam); return result; } /// <summary> /// 修改訂單 /// </summary> public int UpdateOrder(Order param) { int result = 0; if (!String.IsNullOrEmpty(param.OrderNo)) { string sql = "UPDATE [Order$] SET ProductName=@ProductName,Quantity=@Quantity,Money=@Money WHERE OrderNo=@OrderNo"; OleDbParameter[] sqlParam = new OleDbParameter[] { new OleDbParameter("@OrderNo",param.OrderNo), new OleDbParameter("@ProductName",param.ProductName), new OleDbParameter("@Quantity", param.Quantity), new OleDbParameter("@Money", param.Money) }; result = ExcelHelper.ExecuteCommand(sql, sqlParam); } return result; } /// <summary> /// 刪除訂單 /// </summary> public int DeleteOrder(Order param) { int result = 0; if (!String.IsNullOrEmpty(param.OrderNo)) { string sql = "DELETE [Order$] WHERE OrderNo=@OrderNo"; OleDbParameter[] sqlParam = new OleDbParameter[] { new OleDbParameter("@OrderNo",param.OrderNo), }; result = ExcelHelper.ExecuteCommand(sql, sqlParam); } return result; } } }

以上就是C#操作Excel資料增刪改查樣本的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.