一.必须完整安装office,或者在安装office的时候选中‘支持可编程’一项并安装
二. 添加命名控件
using Microsoft.Office.Interop.Excel;
using System.Diagnostics;
三. 添加按钮,引发click事件
Code
1 private void button1_Click(object sender, EventArgs e)
2 {
3 SaveFileDialog save = new SaveFileDialog();
4 save.DefaultExt = "xls";
5 save.Filter = "Excel文件|*.xls";
6
7 String fileName = String.Empty;
8
9 if (save.ShowDialog() == DialogResult.OK)
10 {
11 fileName = save.FileName;
12 }
13
14 Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();//表示Excel应用程序
15 Workbooks workbooks = xlApp.Workbooks; //workbook对象的集合
16 Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); //表示一个workbook
17 Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; //返回workbook的第一个worksheet
18
19 //插入数据
20 for (int i = 0; i < 5; i++)
21 {
22 //设定一定范围内单元格的格式
23 Microsoft.Office.Interop.Excel.Range myrange = worksheet.get_Range(worksheet.Cells[1, 1],worksheet.Cells[1, 5]);
24 myrange.NumberFormatLocal = "@";//文本格式
25
26 worksheet.Cells[1, i + 1] = "00" + i.ToString();//为单元格赋值
27 }
28
29
30 //保存及退出
31 workbook.Saved = true;
32 workbook.SaveCopyAs(fileName);
33 xlApp.Quit();
34
35 GC.Collect();//强行销毁
36 Process.Start(fileName); //打开EXCEL
37
38
39 //worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
40 //worksheet.Columns.AutoFit();
41 //worksheet.Columns.AutoOutline();
42 }