[C#]WinForm中DataGrid - 导出Excel文件

在WinForm开发中,经常需要将DataGrid中显示的数据导出各种文件格式。现以导出Excel为例:

1、继承Net的DataGrid

public class DataGridEx : System.Windows.Forms.DataGrid    

2、添加Excel引用

3、编写导出方法

public bool ExportExcel()
        
{
            
return ExportExcel(""
);
        }

        
public bool ExportExcel(string p_ReportName)
        
{
            
if ( this.TableStyles.Count == 0 ) return false
;
            DataGridTableStyle ts 
= this.TableStyles[0
];

            
// 创建表头                    --LeeWenjie    2006-11-21

            Excel.Application xlApp = new Excel.ApplicationClass();
            Excel.Workbook xlBook 
= xlApp.Workbooks.Add(true
);
            Excel.Worksheet xlSheet 
= (Excel.Worksheet)xlBook.Worksheets[1
];
            
            Excel.Range range 
= xlSheet.get_Range(xlApp.Cells[1,1],xlApp.Cells[1
,ts.GridColumnStyles.Count]);
            range.MergeCells 
= true
;
            xlApp.ActiveCell.FormulaR1C1 
=
 p_ReportName;
            xlApp.ActiveCell.Font.Size 
= 20
;
            xlApp.ActiveCell.Font.Bold 
= true
;
            xlApp.ActiveCell.HorizontalAlignment 
=
 Excel.Constants.xlCenter;

            
// 创建列头                    --LeeWenjie 2006-11-21

            int colIndex = 0;
            
int RowIndex = 2
;
            
            
foreach(DataGridColumnStyle cs in
 ts.GridColumnStyles)
            
{
                colIndex
++
;
                xlSheet.Cells[RowIndex,colIndex] 
=
 cs.HeaderText;
            }

            // 根据Grid显示的内容输出自Excel
            // 赋值给单元格
            int RowCount = this.BindingContext[this.DataSource,this.DataMember].Count;
            
for(int i = 0 ; i < RowCount ;i++
)
            
{
                RowIndex
++
;
                
int ColCount =
 ts.GridColumnStyles.Count;
                
for(colIndex = 1; colIndex <= ColCount ;colIndex++
)
                
{
                    xlSheet.Cells[RowIndex,colIndex] 
= this[i,colIndex-1
];
                }

                Application.DoEvents();
            }

            
            xlBook.Saved  
= true;
            xlBook.SaveCopyAs(
"D://Fly" + DateTime.Now.ToString("yyyyMMdd"+ ".xls"
);
            xlApp.Quit();
            GC.Collect();
            
return true
;
        }


开发环境:
VS.Net 2003

缺陷:导出速度慢,曾考虚过多线程,但效果并不理想。
8000条数据大约需要6分钟。请高手多指教!

**************************************
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值