在事件里调用 this.Export("application/ms-excel", "凭证导出" + DateTime.Now.ToString("yyyyMMddhhmmss")); 即可
private void Export(string FileType, string FileName)
{
switch (FileType)
{
case "application/ms-excel":
ExportExcel(GetOutHtml(), FileName);
break;
default:
break;
}
}
private string GetOutHtml()
{
StringBuilder str = new StringBuilder();
this.ddlexportStarteHide.Value = this.ddlExportState.SelectedValue.ToString();
DataTable dt = this.GetGridViewDataSource();
if (dt != null && dt.Rows.Count > 0)
{
this.nodatainfo1.Visible = false;
}
else
{
this.nodatainfo1.Visible = true;
}
str.Append("<table border=\"1\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\"");
str.Append("<tr class=\"rbsListcss\" style=\"color:Black;background-color:#ABCBF5;font-weight:normal;height:24px;white-space:nowrap;\">");
string rowHeaderColumn = VoucherDetailGrid.RowHeaderColumn;
for (int ii = 1; ii < VoucherDetailGrid.Columns.Count; ii++)
{
str.Append("<th scope=\"col\">" + VoucherDetailGrid.HeaderRow.Cells[ii].Text + "</th>");
}
str.Append("</tr>");
if (dt != null && dt.Rows.Count > 0)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
str.Append("<tr class=\"rbsListRowcss\" align=\"left\" style=\"color:#333333;background-color:White;height:22px;\">");
for (int i = 2; i < dt.Columns.Count; i++)
{
str.Append("<td>");
str.Append(dt.Rows[j][i].ToString());
str.Append("</td>");
}
str.Append("</tr>");
}
}
str.Append("</table>");
return str.ToString();
}
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="outHtml"></param>
/// <param name="fileName"></param>
private void ExportExcel(string outHtml, string fileName)
{
StringBuilder sw = new StringBuilder();
sw.Append("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
sw.Append("<head>");
sw.Append("<!--[if gte mso 9]>");
sw.Append("<xml>");
sw.Append(" <x:ExcelWorkbook>");
sw.Append(" <x:ExcelWorksheets>");
sw.Append(" <x:ExcelWorksheet>");
sw.Append(" <x:Name>" + "sheet1" + "</x:Name>");
sw.Append(" <x:WorksheetOptions>");
sw.Append(" <x:Print>");
sw.Append(" <x:ValidPrinterInfo />");
sw.Append(" </x:Print>");
sw.Append(" </x:WorksheetOptions>");
sw.Append(" </x:ExcelWorksheet>");
sw.Append(" </x:ExcelWorksheets>");
sw.Append("</x:ExcelWorkbook>");
sw.Append("</xml>");
sw.Append("<![endif]-->");
sw.Append("</head>");
sw.Append("<body>");
sw.Append(outHtml);
sw.Append("</body>");
sw.Append("</html>");
Response.ClearContent();
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
string s = HttpUtility.UrlEncode(System.Text.UTF8Encoding.UTF8.GetBytes(fileName));
Response.AppendHeader("Content-Disposition", "attachment; filename=" + s + ".xls");
Response.Write(sw.ToString());
}