方法:根据DataTable列名动态创建GridControl,然后利用GridView导出Excel,同时还可以导出其他形式文件。
[csharp] view plain copy
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
[csharp] view plain copy
///
/// 导出Excel
///
///
public void Export(DataTable datasource)
{
System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
saveFileDialog.DefaultExt = "xls";
saveFileDialog.Filter = "Excel文件|*.xls";
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
GridControl grid= new GridControl();;
GridView view = new GridView();
grid.ViewCollection.Add(view);
grid.MainView = view;
view.GridControl = grid;
foreach (DataColumn dc in datasource.Columns)
{
DevExpress.XtraGrid.Columns.GridColumn gridColumnNumber = view.Columns.AddVisible(dc.ColumnName);
gridColumnNumber.FieldName = dc.ColumnName;
}
grid.DataSource = datasource;
this.Controls.Add(grid);//重要
grid.ForceInitialize();//重要
view.BestFitColumns();
view.ExportToXls(saveFileDialog.FileName);
}
}
关键两行代码必须有,否则view.DataSource为Null
标签:导出,控件,devexpress