最近一个项目中有导出Word的需求,客户要求,应用客户给的Word 模板,根据不同的数据(填空),生成Word,并下载到客户端!
我用到的方式是下面说道的方法2,很容易就实现了上述功能,但是,在客户那边去出现了如下问题:
用户点击“导出”按钮,系统提示下载,客户直接点击“打开”,浏览Word,但是,“这样的操作不能同时开两个Word,
如果开第二个Word,就显示空白,Word文件打不开,但,如果保存到本地后,就可以打开。”
这个问题困扰了我很久,最后,原来是我的一个小失误造成的。看下面分解。
ASP.NET开发中,经常会有把数据导出到Word的需求,其实现方式也有多种,归纳为以下三类:
1:通过Office的组件开发
2:通过代码生成Html,再加文件头(application/ms-html)
3:组件开发(推荐个不错的组件:OfficeWriter)
方法一:
网路上已经有很多代码了,这里不详细说。
流程:在项目中应用office的类库,VS自动转换为dll,在C#中调用dll的方法,save()生成word文件,
在通过程序下载或发送到客户端。
方法二:
网络上也很多代码了。
流程:通过程序构造Html,在给文件加入头,类型,在通过Response.Write(strWord);方法发送到客户端.
如:我们可以把Word另存为Html模板文件,通过程序加载,在替换其中的字符串为我们要的值。
public string ExprotMissionToWord(int id,string templatePath)
{
StreamReader sr = new StreamReader(templatePath,Encoding.UTF7);
sb.Append(sr.ReadToEnd());
sr.Close();
sb.Replace("«Now»", missionDR["Now"].ToString());
sb.Replace("«Ent_Nom»", missionDR["Ent_Nom"].ToString());
sb.Replace("«ETy1»", missionDR["Ent_Type1"].ToString());
sb.Replace("«ETy2»", missionDR["Ent_Type2"].ToString());
return sb.ToString();
}
string strWord= exportManager.ExprotMissionToWord(id,templatePath);
//Response Word File To Client
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment;filename="+fileName+".doc"); //这就是我失误的地方 attachment 写成了 inline
Response.AddHeader("Content-type", "application");
Response.ContentType = "application/ms-html";
Response.Write(strWord);
Response.Flush();
Response.Close();
{
StreamReader sr = new StreamReader(templatePath,Encoding.UTF7);
sb.Append(sr.ReadToEnd());
sr.Close();
sb.Replace("«Now»", missionDR["Now"].ToString());
sb.Replace("«Ent_Nom»", missionDR["Ent_Nom"].ToString());
sb.Replace("«ETy1»", missionDR["Ent_Type1"].ToString());
sb.Replace("«ETy2»", missionDR["Ent_Type2"].ToString());
return sb.ToString();
}
string strWord= exportManager.ExprotMissionToWord(id,templatePath);
//Response Word File To Client
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment;filename="+fileName+".doc"); //这就是我失误的地方 attachment 写成了 inline
Response.AddHeader("Content-type", "application");
Response.ContentType = "application/ms-html";
Response.Write(strWord);
Response.Flush();
Response.Close();
浙公网安备 33010602011771号