本例采用的做法是:在后台调用服务器上一个已做好的word模板(含书签),使用word自带的功能对模板的内容进行编辑,完成后将改新的word保存在服务器上(比如MyNew1.doc),客户端再使用一个ocx控件打开服务器上的这个文件MyNew1.doc(也可以用respose方法输出)。

备注:本实例默认模板为:ProjectZJQualityFlow.doc。本使用了ajax方法获取服务器word所在路径,当然也可以使用隐藏域(input type="hidden" )在PageLoad中赋值路径,然后在js中获得隐藏域中的路径值。

cs的一个类:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Office;
using Microsoft.Office.Core;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Word;
using Microsoft.Office.Tools.Word;

using PinMing.ProjectManage.BLL;
using System.IO;
/// <summary>
/// word模板创建工厂类
/// </summary>
public class ClsWordFactory
{
    /// <summary>
    /// 工程造价咨询word打印模板枚举
    /// </summary>
    public enum WordModelEnum
    {
        /// <summary>
        /// 工程造价咨询质量控制流程单
        /// </summary>
        eProjectZJQualityFlow,

/// <summary>
        /// 征求意见稿回执单
        /// </summary>
        eSolicitIdeaReturnReceipt

}
    string path = "Document/"; //ConfigurationManager.AppSettings["UpFilePath"].ToString().Substring(1);
    Microsoft.Office.Interop.Word.Document wDoc = null;
    Microsoft.Office.Interop.Word.Application wApp = null;

public ClsWordFactory()
    {

}

/// <summary>
    /// 创建打印单
    /// </summary>
    /// <param name="wordTypeEnum">工程造价咨询word打印模板枚举</param>
    /// <param name="expertid">项目关键字ID</param>
    public string CreateWord(WordModelEnum wordTypeEnum, string expertid)
    {
        string docUrl = string.Empty;
        switch (wordTypeEnum)
        {
            case WordModelEnum.eProjectZJQualityFlow:

BLLOrderXYXZ bll = new BLLOrderXYXZ();
                DataTable dt = bll.GetProInfo(expertid).Tables[0];

docUrl = CreateProjectZJQualityFlow(dt, expertid);
                break;

case WordModelEnum.eSolicitIdeaReturnReceipt:
                return string.Empty;
                break;
        }
        return docUrl;
    }

#region 工程造价咨询质量控制流程单

/// <summary>
    /// 工程造价咨询质量控制流程单
    /// </summary>
    /// <returns></returns>
    private string CreateProjectZJQualityFlow(DataTable projectDt, string expertid)
    {
        string url = HttpContext.Current.Server.MapPath("Templet//ProjectZJQualityFlow.doc");

this.OpenWordDocument(url, ref wDoc, ref wApp);
        object oEndOfDoc = "\\endofdoc";
        object missing = System.Reflection.Missing.Value;
        int wordEndRowIndex = 4;//添加行的首行号
        //设定书签部分的数据
        SetBookMarkData(wApp, projectDt);

//设定专业咨询人员
        Microsoft.Office.Interop.Word.Table wordUserTable = wDoc.Tables[1];
        SetUserTableView(wordUserTable, expertid, ref wDoc, ref wApp, ref wordEndRowIndex);

//收尾工作  
        SetEndPartTableView(wDoc, wApp, ref missing, expertid);

// return "../Document/OfficeBak" + expertid + ".doc";

return "WordReport/" + path + "WordPrintBak/" + expertid + ".doc";
    }

/// <summary>
    /// 设定专业咨询人员
    /// </summary>
    /// <param name="wordTable"></param>
    /// <param name="wDoc"></param>
    /// <param name="WApp"></param>
    /// <returns></returns>
    private bool SetUserTableView(Microsoft.Office.Interop.Word.Table wordTable, string expertid, ref Microsoft.Office.Interop.Word.Document wDoc, ref Microsoft.Office.Interop.Word.Application WApp, ref int startrow)
    {
        BLLOrderXYXZ bll = new BLLOrderXYXZ();
        DataSet cpxx = bll.GetProjectSJRY(expertid);//获取审计人员列表
        if (cpxx == null || cpxx.Tables[0].Rows.Count <= 0)
        {
            return false;
        }

object Rownum = cpxx.Tables[0].Rows.Count;
        object Columnnum = 1;
        startrow = startrow + 1;//加上标题行
        wordTable.Cell(startrow, 2).Split(ref Rownum, ref Columnnum);
        wordTable.Cell(startrow, 3).Split(ref Rownum, ref Columnnum);
        wordTable.Cell(startrow, 4).Split(ref Rownum, ref Columnnum);

for (int i = 0; i < cpxx.Tables[0].Rows.Count; i++)
        {
            wordTable.Cell(startrow + i, 2).Range.Text = cpxx.Tables[0].Rows[i]["SJRY"].ToString();
            wordTable.Cell(startrow + i, 3).Range.Text = cpxx.Tables[0].Rows[i]["SUBJECT"].ToString();
            wordTable.Cell(startrow + i, 4).Range.Text = cpxx.Tables[0].Rows[i]["ZYTYPENAME"].ToString();
           
        }
        startrow = startrow + cpxx.Tables[0].Rows.Count;
        return true;
    }

#endregion

#region 通用的方法

/// <summary>
    /// 设定标签数据
    /// </summary>
    /// <param name="application">word的应用</param>
    /// <param name="dt">数据源</param>
    private void SetBookMarkData(Microsoft.Office.Interop.Word.Application application, DataTable dt)
    {

System.Collections.IEnumerator enu = application.ActiveDocument.Bookmarks.GetEnumerator();
        int len = application.ActiveDocument.Bookmarks.Count;
        string[] strbook = new string[len];//dt.Columns.Count
        int i = 0;
        Microsoft.Office.Interop.Word.Bookmark bk = null;
        while (enu.MoveNext())
        {
            bk = (Microsoft.Office.Interop.Word.Bookmark)enu.Current;

if (bk.Name.ToString().Trim() != "Table")
            {
                strbook[i] = bk.Name.ToString();
                i++;
            }
        }

object tempobject = null;
        int length = 0;
        for (i = 0; i < strbook.Length; i++)
        {
            tempobject = strbook[i].ToString();
            if (application.ActiveDocument.Bookmarks.Exists(strbook[i].ToString()))
            {
                application.ActiveDocument.Bookmarks.get_Item(ref tempobject).Select();
                try
                {
                    application.Selection.Text = dt.Rows[0][strbook[i]].ToString();
                }
                catch
                {
                    continue;
                }
            }

}
    }

/// <summary>
    /// 收尾工作
    /// </summary>
    /// <param name="document">文档</param>
    /// <param name="application">应用</param>
    /// <param name="missing"></param>
   private void SetEndPartTableView(Microsoft.Office.Interop.Word.Document document, Microsoft.Office.Interop.Word.Application application, ref object missing, string expertid)
    {
        object o = null;
        string directoryUrl = path + "WordPrintBak/";
        directoryUrl = directoryUrl.Replace("\\\\", "\\");

string directoryUrl2 = HttpContext.Current.Server.MapPath(directoryUrl);
        if (!Directory.Exists(directoryUrl2))    //文件夹不存在 创建它
        {
            Directory.CreateDirectory(directoryUrl2);
        }
        object sFileName = HttpContext.Current.Server.MapPath(directoryUrl + expertid + ".doc");

if (document.SaveFormat == (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument)
        {
            document.Application.ActiveDocument.SaveAs(ref sFileName, ref missing, ref missing,
            ref missing, ref missing, ref missing,
            ref missing, ref missing,
            ref missing, ref missing,
            ref missing, ref missing, ref missing,
            ref missing, ref missing, ref missing);
        }

document.Close(ref missing, ref missing, ref missing);
        wApp.Quit(ref missing, ref missing, ref missing);

if (document != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(document);
            document = null;
        }

if (wApp != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wApp);
            wApp = null;
        }

GC.Collect();
   }

/// <summary>
    /// 打开word模板和word文件
    /// </summary>
    /// <param name="fileName">文件名称(模板所在路径)</param>
    /// <param name="document"></param>
    /// <param name="application"></param>
    private void OpenWordDocument(string wordFileName, ref Microsoft.Office.Interop.Word.Document document, ref Microsoft.Office.Interop.Word.Application appliction)
    {
        if (wordFileName == "") return;
        Microsoft.Office.Interop.Word.Document thisDocument = null;
        Microsoft.Office.Interop.Word.FormFields formFields = null;
        //Microsoft.Office.Interop.Word.Application thisApplication = new Microsoft.Office.Interop.Word.Application();//.NET4.0下写法
        Microsoft.Office.Interop.Word.Application thisApplication = new Microsoft.Office.Interop.Word.ApplicationClass(); //.NET2.0下写法
       // thisApplication.Visible = false;
        thisApplication.Caption = "";
        thisApplication.Options.CheckSpellingAsYouType = false;
        thisApplication.Options.CheckGrammarAsYouType = false;

Object filename = wordFileName;
        Object ConfirmConversions = false;
        Object ReadOnly = true;
        Object AddToRecentFiles = false;

Object PasswordDocument = System.Type.Missing;
        Object PasswordTemplate = System.Type.Missing;
        Object Revert = System.Type.Missing;
        Object WritePasswordDocument = System.Type.Missing;
        Object WritePasswordTemplate = System.Type.Missing;
        Object Format = System.Type.Missing;
        Object Encoding = System.Type.Missing;
        Object Visible = System.Type.Missing;
        Object OpenAndRepair = System.Type.Missing;
        Object DocumentDirection = System.Type.Missing;
        Object NoEncodingDialog = System.Type.Missing;
        Object XMLTransform = System.Type.Missing;

try
        {
            Microsoft.Office.Interop.Word.Document wordDoc =
             thisApplication.Documents.Open(ref filename, ref ConfirmConversions,
             ref ReadOnly, ref AddToRecentFiles, ref PasswordDocument, ref PasswordTemplate,
             ref Revert, ref WritePasswordDocument, ref WritePasswordTemplate, ref Format,
             ref Encoding, ref Visible, ref OpenAndRepair, ref DocumentDirection,
             ref NoEncodingDialog, ref XMLTransform);

thisDocument = wordDoc;
            document = wordDoc;
            appliction = thisApplication;
            formFields = wordDoc.FormFields;
        }
        catch (Exception ex)
        {

}
    }

#endregion

}

html代码:

<script>

function OpenFile()
    {
        var url= document.getElementById('hidUrl').value;
        var fileurl='http://'+location.host+ WordReport_WordView.GetDocPath(url).value;
        if(fileurl!='')
            document.getElementById('FramerControl1').Open(fileurl, true);
    }

</script>

<bodyοnlοad="OpenFile()">
    <form id="form1" runat="server">
        <div>

<asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            </asp:UpdatePanel>

<object id="FramerControl1" codebase="dsoframer.ocx#Version=2,2,0,6" height="550px"
                            width="100%" classid="clsid:00460182-9E5E-11D5-B7C8-B8269041DD57">

</object>

</table>
        </div>
    </form>
</body>

html下的cs代码:

public partial class WordReport_WordView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        AjaxPro.Utility.RegisterTypeForAjax(typeof(WordReport_WordView));
        if (!IsPostBack)
        {
            string id = HttpContext.Current.Request["ID"];
            SetWordPrintContent(id);
        }
    }

private void SetWordPrintContent(string itemID)
    {
        ClsWordFactory factory = new ClsWordFactory();
       string docUrl= factory.CreateWord(ClsWordFactory.WordModelEnum.eProjectZJQualityFlow, itemID);

string url = docUrl;
       hidUrl.Value = docUrl;
    
    }

//返回附件基础路径
    [AjaxPro.AjaxMethod]
    public string GetDocPath(string filepath)
    {
        string SavePath = Server.MapPath(Context.Request.Cookies["GetAppPath"].Value ) +"/"+ filepath;
        SavePath = SavePath.Replace(@"\", @"/").Replace(@"\\\",@"\\");
        return Context.Request.Cookies["GetAppPath"].Value + "/" + filepath;
    }
}

最终效果图:

Web应用Word编辑相关推荐

  1. word 编辑域中的汉字_15条Word常用操作教程,简单实用,纯干货分享,收藏备用!...

    点击蓝字 关注我们 1. 去除页眉横线 在页眉插入信息的时候经常会在下面出现一条横线,如果这条横线影响你的视觉. 这时你可以采用下述的两种方法去掉: 用第一种的朋友比较多,即选中页眉的内容后,选取&q ...

  2. avue validate 变为不可编辑_排版技巧——如何用 Word 编辑参考文献

    每个需要写毕业论文的朋友都会发现,修改文献是一件非常痛苦的事情,虽然现在也有很多软件可以编排参考文献,其实 word 本身就可以. 采用合适的编辑方法会方便地做到整齐,规范, 自动排序和交叉引用. 1 ...

  3. office2010表格计算机,2010年职称计算机考试:Word编辑表格

    编辑表格 1.选定单元格: ◆选定一个单元格:指向单元格左边框,当光标变成实心箭头时单击. ◆选定一行:指向该项左外侧,当光标变成实心箭头时单击. ◆选定一列:指向该列顶端的网格线,当光标变成实心箭头 ...

  4. 少儿计算机兴趣小组活动记录,2013年度儿童画兴趣小组活动记录Word编辑

    <2013年度儿童画兴趣小组活动记录Word编辑>由会员分享,可在线阅读,更多相关<2013年度儿童画兴趣小组活动记录Word编辑(16页珍藏版)>请在人人文库网上搜索. 1. ...

  5. plsql如何显示表结构图_【论文攻略】排版技巧——如何用 Word 编辑参考文献

    每个需要写毕业论文的朋友都会发现,修改文献是一件非常痛苦的事情,虽然现在也有很多软件可以编排参考文献,其实 word 本身就可以. 采用合适的编辑方法会方便地做到整齐,规范, 自动排序和交叉引用. 1 ...

  6. POI生成Web版Word文件

    POI生成Web版Word文件 1       通过URL的输入流实现 2       直接把Html文本写入到Word文件 所谓的使用POI生成Web版Word文件是指利用POI将Html代码插入到 ...

  7. 服务器控件下拉框显示隐藏,演练:在 GridView Web 服务器控件中编辑时显示下拉列表...

    演练:在 GridView Web 服务器控件中编辑时显示下拉列表 08/18/2008 本文内容 更新:2007 年 11 月 GridView 控件默认显示用于编辑的文本框.可以使用 ASP.NE ...

  8. 如何用Word编辑参考文献(转)

    每个需要写毕业论文的朋友都会发现,修改文献是一件非常痛苦的事情,虽然现在也有很多软件可以编排参考文献,其实word本身就可以,这是我师兄教我的^_^,转教大家^_^ 采用合适的编辑方法会方便地做到整齐 ...

  9. 【转】如何用Word编辑参考文献

    每个需要写毕业论文的朋友都会发现,修改文献是一件非常痛苦的事情,虽然现在也有很多软件可以编排参考文献,其实word本身就可以. 采用合适的编辑方法会方便地做到整齐,规范,自动排序和交叉引用. 1.以尾 ...

最新文章

  1. 线段检测M-LSD 已开源
  2. Objective-C中.h、.m、.mm的区别
  3. 1、HTML 初步认识
  4. linxu安装OSX
  5. __attribute__ 之weak,alias属性
  6. python常用模块教程_盘点Python常用的模块和包
  7. MAVEN自定义项目骨架
  8. esayexcel下载问题
  9. 智能排班系统、班次、班表、考勤、年假、调休、审批、请假、培训、值班、换班、加班、工时、自动排班、智能预测、人力需求预测、授权、团队、锁定量排、规则权重设置、菜单、角色、数据监控、工作台、axure
  10. 关押罪犯 扩展域并查集
  11. assetbundle能不能删除_Addressable卸载单个资源的疑问
  12. 【WH】MVC数据分页扩展类
  13. js操作动态表格内元素
  14. 将java或javaweb项目打包为jar包或war包
  15. entrez检索系统要服务器吗,Entrez 系统
  16. 2019年DNS服务器速度排行榜
  17. 基于Hadoop的云计算平台配置
  18. 城市按A-Z json表
  19. 如何启用计算机网络,启用网络发现,教您win10怎么启用网络发现
  20. JavaScript(WebAPI) (前端)

热门文章

  1. 什么是seo?seo的定义
  2. 大数据时代,Wyn Enterprise和您一起探讨CIO的困境和出路 ZT
  3. http://hlhpyasd.iteye.com/blog/865865
  4. mysql 连接间歇性失联解决办法
  5. OpenFaaS实战之二:函数入门
  6. .net core 3.1精伦身份证读卡器IDR210-2(部标版)二次开发
  7. SwiftUI中如何使用App Tracking Transparency Framework
  8. 「解析」Self-Attention 关键点
  9. Oracle数据库的常见漏洞及注入语句
  10. 疫情中的日本东京it工作