博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#操作Excel数据增删改查(转)
阅读量:5790 次
发布时间:2019-06-18

本文共 15223 字,大约阅读时间需要 50 分钟。

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  {      ///       /// Excel文件处理类      ///       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;              }          }            ///           /// 执行无参数的SQL语句          ///           /// SQL语句          /// 
返回受SQL语句影响的行数
public static int ExecuteCommand(string sql) { OleDbCommand cmd = new OleDbCommand(sql, Connection); int result = cmd.ExecuteNonQuery(); connection.Close(); return result; } /// /// 执行有参数的SQL语句 /// /// SQL语句 /// 参数集合 ///
返回受SQL语句影响的行数
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; } /// /// 返回单个值无参数的SQL语句 /// /// SQL语句 ///
返回受SQL语句查询的行数
public static int GetScalar(string sql) { OleDbCommand cmd = new OleDbCommand(sql, Connection); int result = Convert.ToInt32(cmd.ExecuteScalar()); connection.Close(); return result; } /// /// 返回单个值有参数的SQL语句 /// /// SQL语句 /// 参数集合 ///
返回受SQL语句查询的行数
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; } /// /// 执行查询无参数SQL语句 /// /// SQL语句 ///
返回数据集
public static DataSet GetReader(string sql) { OleDbDataAdapter da = new OleDbDataAdapter(sql, Connection); DataSet ds = new DataSet(); da.Fill(ds, "UserInfo"); connection.Close(); return ds; } /// /// 执行查询有参数SQL语句 /// /// SQL语句 /// 参数集合 ///
返回数据集
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; } } }
View Code

2、 创建实体类

2.1 创建UserInfo.cs类,用户信息实体类。

using System;  using System.Collections.Generic;  using System.Linq;  using System.Text;  using System.Data;    namespace MyStudy.Model  {      ///       /// 用户信息实体类      ///       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; }            ///             /// 将DataTable转换成List数据            ///             public static List
ToList(DataSet dataSet) { List
userList = new List
(); 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; } } }
View Code

2.2 创建Order.cs类,订单实体类。

using System;  using System.Collections.Generic;  using System.Linq;  using System.Text;  using System.Data;    namespace MyStudy.Model  {      ///       /// 订单实体类      ///       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; }            ///           /// 将DataTable转换成List数据          ///           public static List
ToList(DataSet dataSet) { List
orderList = new List
(); 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; } } }
View Code

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  {      ///       /// 用户信息业务类      ///       public class UserInfoBLL      {          ///             /// 查询用户列表            ///             public List
GetUserList() { List
userList = new List
(); string sql = "SELECT * FROM [UserInfo$]"; DataSet dateSet = ExcelHelper.GetReader(sql); userList = UserInfo.ToList(dateSet); return userList; } ///
/// 获取用户总数 /// public int GetUserCount() { int result = 0; string sql = "SELECT COUNT(*) FROM [UserInfo$]"; result = ExcelHelper.GetScalar(sql); return result; } ///
/// 新增用户信息 /// 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; } ///
/// 修改用户信息 /// 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; } ///
/// 删除用户信息 /// 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; } } }
View Code

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  {      ///       /// 订单业务类      ///       public class OrderBLL      {          ///             /// 查询订单列表            ///             public List
GetOrderList() { List
orderList = new List
(); string sql = "SELECT * FROM [Order$]"; DataSet dateSet = ExcelHelper.GetReader(sql); orderList = Order.ToList(dateSet); return orderList; } ///
/// 获取订单总数 /// public int GetOrderCount() { int result = 0; string sql = "SELECT COUNT(*) FROM [Order$]"; result = ExcelHelper.GetScalar(sql); return result; } ///
/// 新增订单 /// 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; } ///
/// 修改订单 /// 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; } ///
/// 删除订单 /// 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; } } }
View Code

 

转载于:https://www.cnblogs.com/MirageFox/p/4919672.html

你可能感兴趣的文章
js设置定时器
查看>>
数据库除运算
查看>>
LeetCode--112--路径总和
查看>>
DeviceIOControl与驱动层 - 缓冲区模式
查看>>
感悟贴2016-05-13
查看>>
vim使用教程
查看>>
JDK在LINUX系统平台下的部署案例与总结
查看>>
跨vlan通信-----单臂路由技术
查看>>
百度编辑器ueditor 光标位置的坐标
查看>>
DEV-C++ 调试方法简明图文教程(转)
查看>>
VS2017+EF+Mysql生成实体数据模型(解决闪退的坑)
查看>>
C++多态、继承的简单分析
查看>>
库克称未来苹果用户可自己决定是否降频 网友:你是在搞笑吗?
查看>>
6倍性能差100TB容量,阿里云POLARDB咋实现?
查看>>
Sublime Text 2 技巧
查看>>
使用fscanf()函数从磁盘文件读取格式化数据
查看>>
参加婚礼
查看>>
h5 audio相关手册
查看>>
刚毕业从事java开发需要掌握的技术
查看>>
CSS Custom Properties 自定义属性
查看>>