自动化允许由编程语言(如C#.NET等)创建的应用程序操作其它的应用程序。使用Excel自动化可以创建工作薄(Workbook)并为其添加数据或者创建一个图表。下面的示例演示了把DataSet中的数据导出到Excel中。
1. 新建C#.NET工程ExcelApp。
2. 引用Com组件Microsoft.Excel 11.0 Object Library。
3. 新建类ExcelProgram。
using System;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;
namespace Avisnet
{
class ExcelProgram
{
static void
{
ExcelProgram p = new ExcelProgram();
DataTable table = p.LoadDataTable();
p.ExportDataTable(table);
}
public DataTable LoadDataTable()
{
string connString = "server=wangjs;User ID=sa;Password=sa;database=pubs;Connection Reset=FALSE";
using(SqlConnection conn = new SqlConnection(connString))
{
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM authors", conn);
adapter.Fill(ds);
return ds.Tables[0];
}
}
public void ExportDataTable(DataTable table)
{
// Starts excel and gets an excel application object.
Excel.Application excel = new Excel.Application();
// Adds a new workbook to the excel application.
Excel.Workbook book = excel.Workbooks.Add(Missing.Value);
Excel.Worksheet sheet = (Excel.Worksheet)book.ActiveSheet;
// Adds table headers
for(int col = 0; col < table.Columns.Count; col++)
{
sheet.Cells[1, col + 1] = table.Columns[col].ColumnName;
}
for(int row = 0; row < table.Rows.Count; row++)
{
for(int col = 0; col < table.Columns.Count; col++)
{
sheet.Cells[row + 2, col + 1] = table.Rows[row][col].ToString();
}
}
// Saves and cloeses the workbook;
book.Close(true, "C:\\fx.xls", Missing.Value);
// Exit excel application.
excel.Quit();
}
}
}