C# DataGridView导出Excel
作者:网络转载 发布时间:[ 2013/12/27 15:28:45 ] 推荐标签:C# 开发
第二种方法:引用Excel组件,先定义Excel对象(实例),再根据DataGridView中数据,一格一格去填充Excel对象(实例),单元格,后保存Excel对象(实例)[调用对象Save()方法].
1
2 /// <summary>
3
4 /// 另存新档按钮 导出成Excel
5
6 /// </summary>
7
8 private void SaveToExcel() //另存新档按钮 导出成Excel
9
10 {
11
12 SaveFileDialog saveFileDialog = new SaveFileDialog();
13
14 saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
15
16 saveFileDialog.FilterIndex = 0;
17
18 saveFileDialog.RestoreDirectory = true;
19
20 saveFileDialog.CreatePrompt = true;
21
22 saveFileDialog.Title = "Export Excel File To";
23
24
25 saveFileDialog.ShowDialog();
26
27 string strName = saveFileDialog.FileName;
28
29
30
31 System.Reflection.Missing miss = System.Reflection.Missing.Value;
32
33
34 Excel.Application excel = new Excel.ApplicationClass();
35
36 Excel.Workbooks books = (Excel.Workbooks)excel.Workbooks;
37
38 Excel.Workbook book = (Excel.Workbook)(books.Add(miss));
39
40 Excel.Worksheet sheet = (Excel.Worksheet)book.ActiveSheet;
41
42 sheet.Name = "test";
43
44
45 int colIndex=0;
46
47 foreach (DataGridViewColumn column in dgvAgeWeekSex.Columns)
48
49 {
50
51 colIndex++;
52
53 excel.Cells[1, colIndex] = column.HeaderText;
54
55 }
56
57
58 for (int i = 0; i < dgvAgeWeekSex.Rows.Count; i++)
59
60 {
61
62 for (int j = 0; j < dgvAgeWeekSex.Columns.Count; j++)
63
64 {
65
66 excel.Cells[i + 2, j + 1] = dgvAgeWeekSex.Rows[i].Cells[j].Value.ToString();
67
68 }
69
70 }
71
72
73
74 sheet.SaveAs(strName, miss, miss, miss, miss, miss, Excel.XlSaveAsAccessMode.xlNoChange, miss, miss);
75
76
77
78 book.Close(false, miss, miss);
79
80 books.Close();
81
82 excel.Quit();
83
84
85 //System.Runtime.InteropServices.Marshal.ReleaseComObject();
86
87 System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
88
89 System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
90
91 System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
92
93 System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
94
95 GC.Collect();
96
97 }
98
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11