在aspx文件里加一个按钮,在这里并没有控制js的代码
<asp:Button ID="saveToWord" Text="保存成WORD" CommandArgument="info" runat="server" OnClick="toWORD" />
实际上代码是写在了 Page_Load里
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//给保存按钮添加客户端事件
saveToWord.Attributes.Add("OnClick", "return jsFunction()");
//jsFunction()是js函数
}
}
这个时候就要在aspx里添加js的业务逻辑了
<script language="javascript">
function jsFunction() {
if (confirm("确定保存成doc文件吗?")) {
document.getElementById('savehtml').value = document.getElementById('doc').innerHTML
return true;
}
return false;
}
</script>
在js里我们把aspx里的<input type="hidden" id="savehtml" name="savehtml" value="testinfo" />的值赋值成我们想要保存到doc文件的值。这个时候按钮触发将会post我们的所有input数据到 toWORD按钮事件当中。
当然这个时候提交数据会有不合法数据进入到input当中会提示错误。因为数据里包含了 各种的 < > 标签 那么我们可以
<%@ Page Title="" Language="C#" ValidateRequest="false" MasterPageFile="MasterPage.master" AutoEventWireup="true" CodeFile="testid.aspx.cs" Inherits="testid" EnableEventValidation="false" %>
添加EnableEventValidation="false"就可以不检测数据
下一步就是保存成doc文件并下载了
protected void toWORD(object sender, EventArgs e)
{
string doc = Request.Form["savehtml"];
//以页面视图显示需要添加如下代码
string perfix = "<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:m=\"http://schemas.microsoft.com/office/2004/12/omml\" xmlns=\"http://www.w3.org/TR/REC-html40\">";
string subperfix = "<head><!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val=\"Cambria Math\"/><m:brkBin m:val=\"before\"/><m:brkBinSub m:val=\"--\"/><m:smallFrac m:val=\"off\"/><m:dispDef/><m:lMargin m:val=\"0\"/> <m:rMargin m:val=\"0\"/><m:defJc m:val=\"centerGroup\"/><m:wrapIndent m:val=\"1440\"/><m:intLim m:val=\"subSup\"/><m:naryLim m:val=\"undOvr\"/></m:mathPr></w:WordDocument></xml><![endif]--> </head>";
string endfix="</html>";
doc = perfix + subperfix + doc + endfix;
//Button Btn = sender as Button;
//string commandArgument = Btn.CommandArgument.ToString();
//设置http的头信息,编码格式
//缓冲输出
HttpContext.Current.Response.Buffer = true;
//清空页面输出流
HttpContext.Current.Response.Clear();
//设置输出流的HTTP字符集
HttpContext.Current.Response.Charset = "gb2312";
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
HttpContext.Current.Response.ContentType = "application/ms-word";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=fileDown.doc");
//关闭控件的视图状态,如果仍然为true,RenderControl将启用页的跟踪功能,存储与控件有关的跟踪信息
//this.EnableViewState = false;
//将要下载的页面输出到HtmlWriter
//System.IO.StringWriter writer = new System.IO.StringWriter();
//System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);
//this.RenderControl(htmlWriter);
//提取要输出的内容
//string pageHtml = writer.ToString();
//int startIndex = pageHtml.IndexOf("<div style=\"margin: 0 auto;\" id=\"mainContent\">");
//int endIndex = pageHtml.LastIndexOf("</div>");
//int lenth = endIndex - startIndex;
//pageHtml = pageHtml.Substring(startIndex, lenth);
//输出
// HttpContext.Current.Response.Write(pageHtml.ToString());
HttpContext.Current.Response.Write(doc);
HttpContext.Current.Response.End();
}
总结,基本上就是利用按钮触发js,并通过js把要保存的div标签里的内容通过input回传到按钮事件当中,通过string doc = Request.Form["savehtml"];索取回传数据并保存。例子中的doc = perfix + subperfix + doc + endfix;是吧div包含在hml当中,并且代码中包含了让保存的doc文件在word中以页面视图显示的代码,如果不加上面的代码那么可能在word中以web视图显示
完成。