C# 开发SQL sever数据库数据导出为Excel
时间: 2024-01-22 19:21:31 浏览: 24
你可以使用C#中的Microsoft.Office.Interop.Excel 库将SQL Server数据库数据导出为Excel文件。以下是一个简单的示例代码:
```
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExportToExcel
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword";
string query = "SELECT * FROM myTable";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(reader);
Excel.Application excel = new Excel.Application();
excel.Visible = false;
excel.DisplayAlerts = false;
Excel.Workbook workbook = excel.Workbooks.Add(Type.Missing);
Excel.Worksheet worksheet = workbook.ActiveSheet;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dataTable.Columns[i].ColumnName;
}
for (int i = 0; i < dataTable.Rows.Count; i++)
{
for (int j = 0; j < dataTable.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataTable.Rows[i][j];
}
}
workbook.SaveAs("output.xlsx");
workbook.Close();
excel.Quit();
}
}
}
}
}
```
其中,`connectionString`是数据库连接字符串,`query`是要执行的SQL查询语句,`output.xlsx`是导出的Excel文件名。
请注意,为了使用`Microsoft.Office.Interop.Excel`库,你需要在Visual Studio中添加`Microsoft Excel 16.0 Object Library`引用。你可以在Visual Studio中的“项目”->“添加引用”菜单中找到它。