您的位置:首页 > 编程语言 > C#

【原创】[C#]WinForm中DataGrid扩展 - 导出Excel文件(1)

2006-11-25 00:01 651 查看
[C#]WinForm中DataGrid - 导出Excel文件

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

1、继承Net的DataGrid

public class DataGridEx : System.Windows.Forms.DataGrid
2、添加Excel引用
public bool 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分钟。请高手多指教!

**************************************
本系列相关文章,敬请关注
(完整的DataGridEx原代码,正在整理中,有需要请留言)。
------------------------------------------------------
[C#]WinForm中DataGrid扩展 - 导出Excel文件 (1)
[C#]WinForm中DataGrid扩展 - 快速导出Excel文件 (1)(续)
[C#]WinForm中DataGrid扩展 - 列样式扩展(2)
[C#]WinForm中DataGrid扩展 - 自定义行颜色(3)
[C#]WinForm中DataGrid扩展 - 多列排序(4)
[C#]WinForm中DataGrid扩展 - 自动生成列样式(5)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐