自动化允许由编程语言(如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 Main(string[] args)

...{
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();
}
}
}

本文介绍如何使用C#编程语言将数据从数据库查询结果(DataTable)导出到Microsoft Excel工作簿。通过实例展示了创建Excel文件、填充数据及保存的具体步骤。
1519

被折叠的 条评论
为什么被折叠?



