利用DevExpress将DataTable数据导出到Excel

方法:根据DataTable列名动态创建GridControl,然后利用GridView导出Excel,同时还可以导出其他形式文件。

using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;


 

/// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="datasource"></param>
        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

没有更多推荐了,返回首页