Web应用Word编辑

本例采用的做法是:在后台调用服务器上一个已做好的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>

<bodyonload="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;
    }
}

最终效果图:



原文地址:https://www.cnblogs.com/zhwl/p/2497075.html