// 泛型集合转DataTable,T为Linq实体类
public delegate void GetDataTableRow<T>(T t,System.Data.DataTable d);
public static void ExcelOut2<T>(DataGrid gt, GetDataTableRow<T> GetDataTableRow)
{
ItemCollection list= gt.Items; //获取grid表格的源集合
if (list.Count <= 0) { MessageBox.Show("没有需要导出的数据"); return; }//判断集合是否为空
System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
saveFileDialog.Filter = "Excel files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
//saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出Excel文件到";
//打开选择/创建文件对话框后取消操作
if (saveFileDialog.ShowDialog()== System.Windows.Forms.DialogResult.Cancel)
{
return;
}
System.Data.DataTable dt = new System.Data.DataTable();//创建待传参数DataTable
for (int i = 0; i < gt.Columns.Count; i++)//待传参数DataTable新建列
{
dt.Columns.Add(gt.Columns[i].Header.ToString(), Type.GetType("System.String"));
}
for (int i = 0; i < list.Count; i++)//待传参数DataTable填充内容
{
T t3 = (T)list[i];
GetDataTableRow(t3, dt);
}
WzdhApp.clss_excel.ExcelIO e = new WzdhApp.clss_excel.ExcelIO();//实际调用datatable转excel工具类
bool a = e.DataTableToExecl(dt, saveFileDialog.FileName);
if (a == false)
{
MessageBox.Show("数据导出失败");
}
else {
MessageBox.Show("数据导出成功");
}
}
}
//在程序中使用方法1
GridToExcel.ExcelOut2<KcxxQdxx>(grid_user,(w,d)=> d.Rows.Add(new object[]{w.Wz_bh,w.Wz_Name,w.Wz_ggxh,
w.Fphm,w.Kc_sl,w.Kc_ksysl,w.Wz_jldw,w.Kc_dj,w.Kc_jfsl,
w.Kc_je,w.Rksj,w.Wz_sccj,w.Scrq,w.Wz_bzqx,w.Beizhu }));
//在程序中使用方法2
GridToExcel.ExcelOut2<WZ_DHMX>(grid_user, delegate(WZ_DHMX w,DataTable d) {
DataRow dr = d.NewRow();
dr[0] = w.Wz_Name;
dr[1] = w.KH_DJSXJF;
dr[2] = w.DH_SL;
dr[3] = w.KH_XM;
dr[4] = w.DH_KH;
dr[5] = w.JM_SFZ;
dr[6] = w.KH_XB;
dr[7] = w.JM_LXDH;
dr[8] = w.Create_Date;
dr[9] = w.Rec_clk_name;
d.Rows.Add(dr);
});