search
HomeBackend DevelopmentC#.Net TutorialC# example of adding, deleting, modifying and querying Excel data

C# Operate Excel data by adding, deleting, modifying and checking.

First create the ExcelDB.xlsx file and add two worksheets.

Worksheet 1:

UserInfo table, fields: UserId, UserName, Age, Address, CreateTime.

Worksheet 2:

Order table, fields: OrderNo, ProductName, Quantity, Money, SaleDate.

1. Create the ExcelHelper.cs class, Excel file processing class

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. Create the entity class

2.1 Create the UserInfo.cs class, the user information entity class.

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 Create Order.cs class, order entity class.

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. Create business logic class

3.1 Create UserInfoBLL.cs class, user information business class.

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 Create the OrderBLL.cs class, order business class

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

The above is the content of the C# operation of Excel data addition, deletion, modification and query examples. For more related content, please pay attention to the PHP Chinese website ( www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.