GridControl导出Excel提供了现成的方法ExportToXls,简单使用方法:
private void barExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.FileName = "导出Excel";
fileDialog.Title = "导出Excel";
fileDialog.Filter = "xls文件(*.xls)|*.xls";
DialogResult dialogResult = fileDialog.ShowDialog(this);
if (dialogResult == DialogResult.OK)
{
DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
gridControl1.ExportToXls(fileDialog.FileName, options);
if (XtraMessageBox.Show("导出成功,是否打开", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
System.Diagnostics.Process.Start(fileDialog.FileName);
}
}
往往我们在实际工作中使用Gridcontrol实现复杂的数据展示:多表头,合并单元格,单元格&行自定义背景色和字体、图片等等。在导出Excel时如果仅使用上述代码远不能满足导出的样式。下图GridControl是我将要导出到Excel的
样式设置:
//1、多表头我完全使用Bands,隐藏了原Gridview中Column,因此在打印或导出时候需要将GridView的Columns隐藏
bandedGridView1.OptionsPrint.PrintHeader = false;
//2、行高、列宽设置为GridControl的样式,而非Excel默认高度和宽度
bandedGridView1.OptionsPrint.AutoWidth = false;
bandedGridView1.OptionsPrint.UsePrintStyles = false;
//3、勾选框,这里我使用另一种方式展示:ImageComboBox True-是 Flase-否(自己定义)
DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
options.TextExportMode = DevExpress.XtraPrinting.TextExportMode.Text;//将列表的展示值作为导出内容,否则导出的就是实际值(这里就是true false)
options.RawDataMode = false;
尤为重要一点:单元格字体样式和背景色一定要使用gridView1_RowStyle(object sender, RowStyleEventArgs e)或者RowCellStyle这两个事件去设置,不要使用CustomDrawCell。这样导出的数据样式就和GridControl展示的一样。
导出的整个代码:
private void barExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.FileName = "导出Excel";
fileDialog.Title = "导出Excel";
fileDialog.Filter = "xls文件(*.xls)|*.xls";
DialogResult dialogResult = fileDialog.ShowDialog(this);
if (dialogResult == DialogResult.OK)
{
this.column1.ColumnEdit = this.repositoryItemImageComboBox1;//绑定ImageComboBox控件用于导出
DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
options.TextExportMode = DevExpress.XtraPrinting.TextExportMode.Text;
options.RawDataMode = false;
bandedGridView1.OptionsPrint.PrintHeader = false;
bandedGridView1.OptionsPrint.AutoWidth = false;
bandedGridView1.OptionsPrint.UsePrintStyles = false;
gridControl1.ExportToXls(fileDialog.FileName, options);
this.column1.ColumnEdit = this.repositoryItemCheckEdit1; //导出成功后,绑定回原控件
if (XtraMessageBox.Show("导出成功,是否打开", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
System.Diagnostics.Process.Start(fileDialog.FileName);
}
}
}
private void gridView1_RowStyle(object sender, RowStyleEventArgs e)
{
GridView view = sender as GridView;
T row = view.GetRow(e.RowHandle) as T;
if (row == null) return;
e.Appearance.BackColor = Color.Yellow;
}
导出Excel效果: