C#与SQL sever数据库 XMind版

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过以下步骤使用 C#SQL Server 数据库数据导出为 Excel 文件: 1. 使用 SQL Server Management Studio (SSMS) 创建一个 SQL 查询,该查询从特定表中选择要导出的数据。 2. 在 Visual Studio 中创建一个新的 C# 控制台应用程序项目。 3. 在该项目中添加对 Microsoft.Office.Interop.Excel 引用的引用。 4. 在代码中,创建一个 SqlConnection 对象并打开连接。 5. 创建一个 SqlCommand 对象,并将查询字符串和 SqlConnection 对象传递给它。 6. 使用 SqlCommand 对象的 ExecuteReader 方法执行查询,并将结果存储在 SqlDataReader 对象中。 7. 创建一个 Excel.Application 对象,并使用它创建一个新的工作簿。 8. 在工作簿中创建一个新的工作表,并将 SqlDataReader 对象中的数据写入该工作表中。 9. 保存 Excel 文件。 以下是 C# 代码示例: ``` using System; using System.Data.SqlClient; using Microsoft.Office.Interop.Excel; namespace SQLtoExcel { class Program { static void Main(string[] args) { string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;"; string queryString = "SELECT * FROM myTable"; SqlConnection connection = new SqlConnection(connectionString); connection.Open(); SqlCommand command = new SqlCommand(queryString, connection); SqlDataReader reader = command.ExecuteReader(); Application excel = new Application(); Workbook workbook = excel.Workbooks.Add(); Worksheet worksheet = (Worksheet)workbook.Worksheets[1]; int row = 1; int column = 1; for (int i = 0; i < reader.FieldCount; i++) { worksheet.Cells[row, column++] = reader.GetName(i); } row++; while (reader.Read()) { column = 1; for (int i = 0; i < reader.FieldCount; i++) { worksheet.Cells[row, column++] = reader[i].ToString(); } row++; } workbook.SaveAs("output.xlsx"); workbook.Close(); excel.Quit(); Console.WriteLine("Data exported to Excel file."); Console.ReadLine(); } } } ``` 请注意,这只是一个简单的示例,您可能需要根据您的需要进行更改和调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值