Winform datagirdview导出Excel 封装方法 好用!!!
Posted baimangguo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Winform datagirdview导出Excel 封装方法 好用!!!相关的知识,希望对你有一定的参考价值。
转自:https://www.cnblogs.com/chaowang/p/6265698.html
1,窗体设计
首先需要引入程序集:Microsoft.Office.Interop.Excel (如果没有引用过的需要右键添加引用再搜索就行了)
实现的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
/// <summary> /// /// </summary> /// <param name="fileName">文件路径</param> /// <param name="myDGV">控件DataGridView</param> private void ExportExcels( string fileName, DataGridView myDGV) { string saveFileName = "" ; SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.DefaultExt = "xls" ; saveDialog.Filter = "Excel文件|*.xls" ; saveDialog.FileName = fileName; saveDialog.ShowDialog(); saveFileName = saveDialog.FileName; if (saveFileName.IndexOf( ":" ) < 0) return ; //被点了取消 Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null ) { MessageBox.Show( "无法创建Excel对象,可能您的机子未安装Excel" ); return ; } Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; //取得sheet1 //写入标题 for ( int i = 0; i < myDGV.ColumnCount; i++) { worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText; } //写入数值 for ( int r = 0; r < myDGV.Rows.Count; r++) { for ( int i = 0; i < myDGV.ColumnCount; i++) { worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value; } System.Windows.Forms.Application.DoEvents(); } worksheet.Columns.EntireColumn.AutoFit(); //列宽自适应 if (saveFileName != "" ) { try { workbook.Saved = true ; workbook.SaveCopyAs(saveFileName); } catch (Exception ex) { MessageBox.Show( "导出文件时出错,文件可能正被打开!
" + ex.Message); } } xlApp.Quit(); GC.Collect(); //强行销毁 MessageBox.Show( "文件: " + fileName + ".xls 保存成功" , "信息提示" , MessageBoxButtons.OK, MessageBoxIcon.Information); } |
点击按钮调用
1
2
3
4
5
|
private void button1_Click( object sender, EventArgs e) { string a = "D:" + "\\KKHMD.xls" ; ExportExcels(a, dataGridView1); } |
完成截图
以上是关于Winform datagirdview导出Excel 封装方法 好用!!!的主要内容,如果未能解决你的问题,请参考以下文章
C#WinForm datagirdview的datapropertyname给每列绑定数据
C# Winform 如何居中DataGirdView中的文本?