C#DevExpress导出数据控件GridView表格中的数据到excel
#region 导出员工信息
private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
DataTable datasource = _EmployeesServices.get_V_EmployeeDataTable("");
if (datasource == null )
{
XtraMessageBox.Show("无法导出数据,请检查");
}
Export(datasource);
}
public void Export(DataTable datasource)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.DefaultExt = "xls";
saveFileDialog.Filter = "Excel文件|*.xls";
if (saveFileDialog.ShowDialog() == 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)
{
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);
XtraMessageBox.Show("导出成功");
}
}
#endregion
_EmployeesServices.get_V_EmployeeDataTable("");
get_V_EmployeeDataTable() 这个方法查询的是视图。如果查表的话 导出来的数据列头是英文