1. 添加引用Micosoft Excel 11.0 Object Library
添加 using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection; // 引用这个才能使用Missing字段
2. 打开一个空Excel文件:
private void btnbrower_Click(object sender, EventArgs e)
{
Excel.Application excel = new Excel.Application();//引用Excel对象
excel.Application.Workbooks.Add ( true );//引用Excel工作簿
excel.Visible = true;//使Excel可视
excel = null; //释放资源
}
3. 打开指定的Excel文件:
private void btnopen_Click(object sender, EventArgs e)
{
Excel.Application ex = new Excel.Application();
Excel.Worksheet exsh = new Excel.Worksheet();
ex.Visible = true;
Excel.Workbook xbook = ex.Workbooks.Open(@"E:/chongxiu.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value,Missing.Value,
Missing.Value, Missing.Value,Missing.Value, Missing.Value, Missing.Value,Missing.Value,
Missing.Value, Missing.Value, Missing.Value);
exsh = (Excel.Worksheet)xbook.Sheets[1];
ex = null;
}
4. 说明:
Application对象: Application对象处于Excel对象层次结构的顶层,表示Excel自身的运行环境。
Workbook对象: Workbook对象直接地处于Application对象的下层,表示一个Excel工作薄文件。
Worksheet对象: Worksheet对象包含于Workbook对象,表示一个Excel工作表。
Range对象: Range对象包含于Worksheet对象,表示Excel工作表中的一个或多个单元格。
在命名空间"Excel"中,还定义了一个类"Cell",这个类所代表的就是Excel表格中的一个单元格。
5. 直接从数据库中读取数据并在Excel中显示:
string constr = "server=LISHIC;uid=sa;pwd=;database=exceltosql";
SqlConnection con = new SqlConnection(constr);
con.Open();
string cmdstr = "select * from exceltosql.dbo.结果";
SqlCommand cmd = new SqlCommand(cmdstr, con);
SqlDataReader reader = cmd.ExecuteReader();
Excel.Application exapp = new Microsoft.Office.Interop.Excel.Application();
exapp.Workbooks.Add(true);
int row = 2;
int fieldcount = 0;
fieldcount = reader.FieldCount; //获取当前行中的列数
for(int col = 0; col < fieldcount; col++)
exapp.Cells[1, col + 1] = reader.GetName(col); //获取指定列的名称
while (reader.Read ())
{
for(int col = 0; col < fieldcount; col++)
exapp.Cells[row, col + 1] = reader.GetValue(col).ToString(); //获取以本机格式表示的指定列的值
row++;
}
exapp.Visible = true;
exapp = null;