public partial class ExportWord : System.Web.UI.Page
{
string pName = string.Empty;//生成的Word文件名
string pContent = string.Empty;//报表内容
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request["pName"]))
pName = Request["pName"].Trim();
else
pName = DateTime.Now.ToString("yyyyMMddHHmmss");
if (!string.IsNullOrEmpty(Request["pContent"]))
pContent = HttpUtility.UrlDecode(Request["pContent"]);
BuildWordInStream();
}
private void BuildWordInStream()
{
Page.Response.Clear();
Page.Response.Buffer = true;
Page.Response.ContentEncoding = System.Text.Encoding.UTF8;
Page.Response.ContentType = "application/octet-stream";//采用流模式,直接下载
//Page.Response.ContentType = "application/msword";//生成的word文件默认打开方式是web视图
Page.Response.AppendHeader("Content-Disposition", "attachment;fileName=" + HttpUtility.UrlEncode(pName + ".doc", System.Text.Encoding.UTF8));
//增加word xml Attributes
System.Text.StringBuilder sb = new System.Text.StringBuilder("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\"><meta name=ProgId content=Word.Document><meta name=Generator content=\"Microsoft Word 11\"><meta name=Originator content=\"Microsoft Word 11\"><link rel=File-List href=\"" + pName + ".files/filelist.xml\"><link rel=Edit-Time-Data href=\"" + pName + ".files/editdata.mso\"><!--[if !mso]><style>v\\:* {behavior:url(#default#VML);}o\\:* {behavior:url(#default#VML);}w\\:* {behavior:url(#default#VML);}.shape {behavior:url(#default#VML);}</style><![endif]--><title> </title><!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:Zoom>0</w:Zoom><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:Compatibility><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel></w:WordDocument></xml><![endif]--><!--[if gte mso 9]><xml><w:LatentStyles DefLockedState=\"false\" LatentStyleCount=\"156\"></w:LatentStyles></xml><![endif]-->");
//可以在此处增加样式
sb.Append("</head><body><form>");
//增加实际内容
sb.Append(pContent);
//页面结束
sb.Append("</form></body></html>");
Response.BinaryWrite(System.Text.Encoding.GetEncoding("UTF-8").GetBytes(sb.ToString()));
Response.Flush();
}


浙公网安备 33010602011771号