winForm导出Excel

一、Microsoft.Office

 1  private void btExportSelect_Click(object sender, EventArgs e)
 2         {
 3             string fileName = "";
 4             string saveFileName = "";
 5             SaveFileDialog saveDialog = new SaveFileDialog();
 6             saveDialog.DefaultExt = "xlsx";
 7             saveDialog.Filter = "Excel文件|*.xlsx";
 8             saveDialog.FileName = fileName;
 9             saveDialog.ShowDialog();
10             saveFileName = saveDialog.FileName;
11             if (saveFileName.IndexOf(":") < 0) return; //被点了取消
12             Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
13             if (xlApp == null)
14             {
15                 MessageBox.Show("无法创建Excel对象,您的电脑可能未安装Excel");
16                 return;
17             }
18 
19             Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
20             Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
21             Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1             
22 
23             //写入标题             
24             for (int i = 0; i < this.dgvStore.ColumnCount; i++)
25             {
26                 worksheet.Cells[1, i + 1] = this.dgvStore.Columns[i].HeaderText;
27             }
28 
29             //写入数值
30             for (int r = 0; r < this.dgvStore.Rows.Count; r++)
31             {
32                 for (int i = 0; i < this.dgvStore.ColumnCount; i++)
33                 {
34                     worksheet.Cells[r + 2, i + 1] = this.dgvStore.Rows[r].Cells[i].Value;
35                 }
36                 System.Windows.Forms.Application.DoEvents();
37             }
38 
39             worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
40             MessageBox.Show(fileName + "资料保存成功", "提示", MessageBoxButtons.OK);
41             if (saveFileName != "")
42             {
43                 try
44                 {
45                     workbook.Saved = true;
46                     workbook.SaveCopyAs(saveFileName);  //fileSaved = true;                 
47                 }
48                 catch (Exception ex)
49                 {//fileSaved = false;                      
50                     MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
51                 }
52             }
53 
54             xlApp.Quit();
55             GC.Collect();//强行销毁
56         }

二、Microsoft.Office

winForm导出Excel

上一篇:C#事件委托、观察者模式、消息中心、消息转发


下一篇:Windows批处理编辑防火墙规则