protected void btnDataOut_Click(object sender,EventArgs e)
{
DataToExcel dte = new DataToExcel();
DataTable dt = null;
if (sid > 0)
{
dt = Users.GetAuthUserListByGroupidList("8",sid.ToString());
}
else
{ dt = Users.GetAuthUserListByGroupid(8); }
UserInfo userInfo = new UserInfo();
if (dt.Rows.Count > 0)
{
dt = ChangeSchema(dt);
foreach (DataRow dr in dt.Rows)
{
userInfo = AdminUsers.GetUserInfo(Convert.ToInt32(dr["uid"].ToString().Trim()));
dr["realname"] = userInfo.Realname.ToString().Trim();
dr["mobile"] = userInfo.Mobile.ToString().Trim();
dr["organization"] = filterIds(dr["organization"].ToString().Trim());
dr["email"] = dr["email"].ToString().Trim();
dr["username"] = dr["username"].ToString().Trim();
if (dr["gender"].ToString() == "0") dr["gender"] = "男";
if (dr["gender"].ToString() == "1") dr["gender"] = "女";
}
}
for (int i = 0; i < dt.Columns.Count; )
{
if (dt.Columns[i].ColumnName.Contains("username") || dt.Columns[i].ColumnName.Contains("realname") || dt.Columns[i].ColumnName.Contains("mobile") || dt.Columns[i].ColumnName.Contains("gender") || dt.Columns[i].ColumnName == "email" || dt.Columns[i].ColumnName.Contains("organization"))
{ i++; }
else
{
dt.Columns.Remove(dt.Columns[i].ColumnName);
dt.AcceptChanges();
}
}
DataTable dtAuth = new DataTable();
dtAuth.Columns.Add("真实姓名",typeof(string));
dtAuth.Columns.Add("性别",typeof(string));
dtAuth.Columns.Add("用户名",typeof(string));
dtAuth.Columns.Add("手机号码",typeof(string));
dtAuth.Columns.Add("所属企业",typeof(string));
dtAuth.Columns.Add("E_mail",typeof(string));
foreach (DataRow dr in dt.Rows)
{
dtAuth.Rows.Add(new Object[] { dr["realname"],dr["gender"],dr["username"],dr["mobile"],dr["organization"],dr["email"] });
}
DataTable2Excel(dtAuth,"userinfo");
}
//dtData是要导出为Excel的DataTable,FileName是要导出的Excel文件名(不加.xls)
private void DataTable2Excel(System.Data.DataTable dtData,String FileName)
{
System.Web.UI.WebControls.GridView dgExport = null;
//当前对话
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
//IO用于导出并返回excel文件
System.IO.StringWriter strWriter = null;
System.Web.UI.HtmlTextWriter htmlWriter = null;
if (dtData != null)
{
//设置编码和附件格式
//System.Web.HttpUtility.UrlEncode(FileName,System.Text.Encoding.UTF8)作用是方式中文文件名乱码
curContext.Response.Charset = "GB2312";
curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
curContext.Response.AddHeader("content-disposition","attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName,System.Text.Encoding.UTF8) + ".xls");
curContext.Response.ContentType = "application nd.ms-excel";
//导出Excel文件
strWriter = new System.IO.StringWriter();
htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
dgExport = new System.Web.UI.WebControls.GridView();
dgExport.DataSource = dtData.DefaultView;
dgExport.AllowPaging = false;
dgExport.DataBind();
//下载到客户端
dgExport.RenderControl(htmlWriter);
curContext.Response.Write(strWriter.ToString());
curContext.Response.End();
}
}
原文链接:https://www.f2er.com/javaschema/286211.html