public void Result( ){try{StringBuilder sql = new StringBuilder();List<SqlParameter> parameters = new List<SqlParameter>(); sql.Append(@"sql 查詢語句");Da ...
public void Result( )
{
try
{
StringBuilder sql = new StringBuilder();
List<SqlParameter> parameters = new List<SqlParameter>();
sql.Append(@"sql 查詢語句");
DataTable dt = DbHelperSQL.Query(sql.ToString()).Tables[0];
StringBuilder TableHead = new StringBuilder();
StringBuilder TableFoot = new StringBuilder();
TableHead.Append("<tr style=\"font-weight: bold; white-space: nowrap;\">")
.Append("<td rowspan =\"2\"></td></tr>")
.Append("<tr></tr>");
TableFoot.Append("<tr><td colspan = \"4\">導出時間:" + DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss") + "</td></tr>");
DataTableToExcel(dt, TableHead.ToString(), TableFoot.ToString(), name + "彙總_" + DateTime.Now.ToString("yyyyMM"));
}
catch (Exception ex)
{
}
}
/// <summary>
/// DataTable導出Excel
/// </summary>
/// <param name="data">集合</param>
/// <param name="ChartHead">表頭</param>
/// <param name="fileName">文件名稱</param>
public static void DataTableToExcel(DataTable data, string ChartHead, string ChartFoot, string fileName)
{
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.Charset = "Utf-8";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName + ".xls", 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(ChartHead);
string NumberAsTextExp = "vnd.ms-excel.numberformat:@";
//寫數據
foreach (DataRow row in data.Rows)
{
sbHtml.Append("<tr>");
for (int i = 0; i < row.ItemArray.Count(); i++)
{
if (row[i].GetType() == typeof(string))
{
sbHtml.Append("<td style='" + NumberAsTextExp + "'>").Append(row[i]).Append("</td>");
}
else
{
sbHtml.Append("<td>").Append(row[i]).Append("</td>");
}
}
sbHtml.AppendLine("</tr>");
}
//寫彙總行
sbHtml.AppendLine(ChartFoot);
sbHtml.AppendLine("</table>");
HttpContext.Current.Response.Write(sbHtml.ToString());
HttpContext.Current.Response.End();
}