C#操作Excel数据增删改查示例

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;
}
}
}

(0)

相关推荐

  • c#利用Excel直接读取数据到DataGridView

    在winform里拖入一个datagridview控件,跟一个openfiledialog控件 复制代码 代码如下: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using Microsoft.Office.Core;using Excel=Mi

  • C#数据导入/导出Excel文件及winForm导出Execl总结

    一.asp.net中导出Execl的方法: 在asp.net中导出Execl有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址输出在浏览器上:一种是将文件直接将文件输出流写给浏览器.在Response输出时,\t分隔的数据,导出execl时,等价于分列,\n等价于换行. 1.将整个html全部输出execl 此法将html中所有的内容,如按钮,表格,图片等全部输出到Execl中. 复制代码 代码如下: Response.Clear(); Response.Buffer= t

  • C#实现的Excel文件操作类实例

    本文实例讲述了C#实现的Excel文件操作类.分享给大家供大家参考,具体如下: using System; using System.Data; using System.Data.OleDb; using System.Text; using System.IO; namespace Hxh.API { /// <summary> /// ExcelOpration 的摘要说明. /// </summary> public class ExcelOpration { OleDbC

  • c#读写excel文件使用示例

    因为支持csv,所以就一块写上了Workbook,Worksheet using Aspose.Cells(第三方) 把Excel读取到属性对象列表,需要传入对象类型和文件路径.例:List<PropSetCurrency> currencyList = this.GetObjectList<PropSetCurrency>(filePath);注:Excel的表头需要和对象名对应(可无序),且第一列不能为空 把属性对象列表保存到Excel,需要传入对象列表和保存的文件完整路径.例

  • c#将Excel数据导入到数据库的实现代码

    假如Excel中的数据如下: 数据库建表如下: 其中Id为自增字段: 代码: 复制代码 代码如下: using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;using System.Data.OleDb;using System.Configuratio

  • C#操作EXCEL DataTable转换的实例代码

    复制代码 代码如下: //加载Excel          public   DataSet LoadDataFromExcel(string filePath)         {             try            {                 string strConn;                 //strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + &qu

  • C#如何将DataTable导出到Excel解决方案

    最近,由于公司项目中需要将系统内用户操作的所有日志进行转存备份,考虑到以后可能还需要还原,所以最后决定将日志数据备份到Excel中. 下面是我项目当中Excel.cs这个类的全部代码,通过这个类可以很容易地将DataTable中的数据导入到Excel方法中. 首先,必须要下载NPOI.dll这个程序集, 类代码如下: 复制代码 代码如下: using System; using NPOI.HSSF; using NPOI.HPSF; using NPOI.HSSF.UserModel; usin

  • C#将html table 导出成excel实例

    复制代码 代码如下: public void ProcessRequest (HttpContext context) { string elxStr = "<table><tbody><tr><td>1</td><td>11</td></tr><tr><td>2</td><td>22</td></tr></tbody>

  • C#实现将DataTable内容输出到Excel表格的方法

    本文实例讲述了C#实现将DataTable内容输出到Excel表格的方法.分享给大家供大家参考.具体如下: 1.关于本文 本文描述了一个函数(SaveToExcel),该函数可以将DataTable数据内的数据输出到Excel表格中 2.相关说明 1)本文中使用这个函数将一个DataTable中的内容输出到路径名为addr的目录下: 复制代码 代码如下: public void SaveToExcel(string addr, System.Data.DataTable dt) 2)这个函数需要

  • C#使用oledb操作excel文件的方法

    本文实例讲述了C#使用oledb操作excel文件的方法.分享给大家供大家参考.具体分析如下: 不管什么编程语言都会提供操作Excel文件的方式,C#操作Excel主要有以下几种方式: 1.Excel 说明:利用Office 的Excel组件来操作excel文件 优点:能够完全操作Excel文件,生成丰富文件内容 缺点:需要电脑安装Excel,会启动Excel进程这在web上很不方便 2.OpenXML 说明:一个操作字处理文档的组件包括Excel 优点:能够操作操作Excel2007版本文件

  • C#导入导出EXCEL文件的代码实例

    复制代码 代码如下: using System;using System.Data;using System.Data.OleDb; namespace ZFSoft.Joint{    public class ExcelIO    {        private int _ReturnStatus;        private string _ReturnMessage; /// <summary>        /// 执行返回状态        /// </summary&g

随机推荐