C#导出word

我是先在服务器放一个模板word,然后将word上的内容替换,保存在服务器,然后再在客户端下载

System.Data.DataTable dtReturn = null;//这是需要的数据,可从数据库查

Document wordDoc = null;

Microsoft.Office.Interop.Word.ApplicationClass wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();

string FileName = "";

//模板word位置

string tempDocPath = HttpContext.Current.Request.PhysicalPath;

tempDocPath += "\\docModel\\myWord.docx";

object missing = Missing.Value;

object tempName = tempDocPath;

String uuid = System.Guid.NewGuid().ToString().Replace("-", "");

FileName = string.Format("{0}{1}{2}", dir, DateTime.Now.ToString("yyyyMMddHHmmss") + "_", uuid + ".docx");

File.Copy(tempDocPath, FileName);

object obj_FileName = FileName;

wordDoc = wordApp.Documents.Add(ref obj_FileName, ref missing, ref missing, ref missing);

//替换模板word的内容

replateDataForDoc(wordApp, dtReturn);

wordDoc.Activate();//设置现在操作的文件

wordDoc.SaveAs2(obj_FileName);//保存文件

wordDoc.Close();//关闭文档对象

wordApp.Quit();

//下载word

DownloadFile(Response, FileName);

其中替换模板word内容的方法:replateDataForDoc()如下:

private void replateDataForDoc(Microsoft.Office.Interop.Word.ApplicationClass wordApp, System.Data.DataTable dataTable)
    {
        string code = dataTable.Rows[0]["name"] != null ? dataTable.Rows[0]["name"].ToString() : "";
        findAndReplace(wordApp, "name", code);
    }
private void findAndReplace(Microsoft.Office.Interop.Word.ApplicationClass wordApp, object findText, object replaceText) {
        int len = replaceText.ToString().Length;   //要替换的文字长度
        int cnt = len / 210;
        string newstr;
        if (len < 220)   //小于220字直接替换
        {
            replaceText = replaceText.ToString().Replace("\n", "^p");
            wordApp.Selection.Find.Execute(FindText: findText, ReplaceWith: replaceText, Replace: WdReplace.wdReplaceAll);
        } else {
            for (int i = 0; i <= cnt; i++) {
                if (i != cnt) {
                    newstr = replaceText.ToString().Substring(i * 210, 210) + findText;  //新的替换字符串
                    newstr = newstr.Replace("\n", "^p");
                    wordApp.Selection.Find.Execute(FindText: findText, ReplaceWith: newstr, Replace: WdReplace.wdReplaceAll);
                } else {
                    newstr = replaceText.ToString().Substring(i * 210, len - i * 210);    //最后一段需要替换的文字
                    newstr = newstr.Replace("\n", "^p");
                    wordApp.Selection.Find.Execute(FindText: findText, ReplaceWith: newstr, Replace: WdReplace.wdReplaceAll);
                }
            }
        }
    }

下载word的方法:DownloadFile()如下:

public static void DownloadFile(System.Web.HttpResponse Response, string FileName) {
            if (FileName == "") {
                return;
            }
            FileInfo fileInfo = new FileInfo(FileName);
            string[] arr_FileName = FileName.Split('\\');
            string strFile = "";
            if (arr_FileName.Length > 0) {
                strFile = arr_FileName[arr_FileName.Length - 1];
            }
            strFile = HttpUtility.UrlEncode(strFile, System.Text.Encoding.UTF8);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment;filename=" + strFile);
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentType = "application/octet-stream";
            //Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.WriteFile(fileInfo.FullName);
            Response.Flush();
            Response.End();
        }





  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值