62,046
社区成员
发帖
与我相关
我的任务
分享
//打印方法
string[] Infos = new string[] { "ID", "Name" };//声明属性的数组
IList<UserInfo> uis = new List<UserInfo>();
uis.Add(new UserInfo { ID = "1", Name = "张三" });
uis.Add(new UserInfo { ID = "2", Name = "李四" });
DataTable dt = new DataTable("123");
dt.Columns.Add("编号", System.Type.GetType("System.String"));
dt.Columns.Add("姓名", System.Type.GetType("System.String"));
for (int i = 0; i < uis.Count; i++)
{
DataRow dr = dt.NewRow();//第一次声明学生属性名称的行
//此处赋值可以循环上边声明的属性数组,简略没有写
dr[0] = "ID";
dr[1] = "Name";
dt.Rows.Add(dr);
dr = dt.NewRow();//第二次声明学生内容的行
dr[0] = uis[i].ID;
dr[1] = uis[i].Name;
dt.Rows.Add(dr);
}
ExportExcel(dt, DateTime.Now.ToString("yyyy-MM-dd") + "学生信息");
/// <summary>
/// Excel导出数据
/// </summary>
/// <param name="data">数据源</param>
/// <param name="fileName">文件名</param>
public static void ExportExcel(DataTable data, string fileName)
{
try
{
if (data != null && data.Rows.Count > 0)
{
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.Charset = "Utf-8";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName + ".xls", System.Text.Encoding.UTF8));
StringBuilder sbHtml = new StringBuilder();
sbHtml.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
sbHtml.AppendLine("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");
//写出列名
sbHtml.AppendLine("<tr style=\"background-color: #FFE88C;font-weight: bold; white-space: nowrap;\">");
foreach (System.Data.DataColumn column in data.Columns)
{
sbHtml.AppendLine("<td>" + column.ColumnName + "</td>");
}
sbHtml.AppendLine("</tr>");
//写数据
foreach (System.Data.DataRow row in data.Rows)
{
sbHtml.Append("<tr>");
foreach (System.Data.DataColumn column in data.Columns)
{
sbHtml.Append("<td>").Append(row[column].ToString()).Append("</td>");
}
sbHtml.AppendLine("</tr>");
}
sbHtml.AppendLine("</table>");
HttpContext.Current.Response.Write(sbHtml.ToString());
HttpContext.Current.Response.End();
}
}
catch (Exception ex)
{
// Logger.WriteLog("-----------Excel导出数据异常-----------\r\n" + ex.ToString() + "\r\n");
}
}
//学生内容类
private class UserInfo
{
public string ID { get; set; }
public string Name { get; set; }
}