先引用 Microsoft.Office.Interop.Excel
再如下导入命名空间:
using System.Data.Common;
using System.Data.SqlClient;
using Excel = Microsoft.Office.Interop.Excel;
using (DbConnection connection = new SqlConnection("server=.; user id=sa;password=***; database=northwind"))
{
connection.Open();
DbCommand command = connection.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "select EmployeeId, FirstName, LastName, Titlefrom dbo.Employees";
var reader = command.ExecuteReader();
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Add();
Excel.Worksheet worksheet = workbook.ActiveSheet as Excel.Worksheet;
var index = 1;
while (reader.Read())
{
worksheet.Cells[index, 1] = reader.GetInt32(0).ToString();
worksheet.Cells[index, 2] = reader.GetString(1);
worksheet.Cells[index, 3] = reader.GetString(2);
worksheet.Cells[index, 4] = reader.GetString(3);
index++;
}
reader.Close();
workbook.SaveAs(@"d:\employees.xlsx");
workbook.Close();
application.Quit();
connection.Close();
}