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).Substring1);
    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 CreateWordWordModelEnum wordTypeEnum, string expertid)
    {
        string docUrl = string.Empty;
        switch wordTypeEnum)
        {
            case WordModelEnum.eProjectZJQualityFlow:

                BLLOrderXYXZ bll = new BLLOrderXYXZ);
                DataTable dt = bll.GetProInfoexpertid).Tables[0];

                docUrl = CreateProjectZJQualityFlowdt, expertid);
                break;

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

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

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

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

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

        //收尾工作  
        SetEndPartTableViewwDoc, 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 SetUserTableViewMicrosoft.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.GetProjectSJRYexpertid);//获取审计人员列表
        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.Cellstartrow, 2).Splitref Rownum, ref Columnnum);
        wordTable.Cellstartrow, 3).Splitref Rownum, ref Columnnum);
        wordTable.Cellstartrow, 4).Splitref Rownum, ref Columnnum);

        for int i = 0; i < cpxx.Tables[0].Rows.Count; i++)
        {
            wordTable.Cellstartrow + i, 2).Range.Text = cpxx.Tables[0].Rows[i][“SJRY”].ToString);
            wordTable.Cellstartrow + i, 3).Range.Text = cpxx.Tables[0].Rows[i][“SUBJECT”].ToString);
            wordTable.Cellstartrow + 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 SetBookMarkDataMicrosoft.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.Existsstrbook[i].ToString)))
            {
                application.ActiveDocument.Bookmarks.get_Itemref 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 SetEndPartTableViewMicrosoft.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.MapPathdirectoryUrl);
        if !Directory.ExistsdirectoryUrl2))    //文件夹不存在 创建它
        {
            Directory.CreateDirectorydirectoryUrl2);
        }
        object sFileName = HttpContext.Current.Server.MapPathdirectoryUrl + expertid + “.doc”);

        if document.SaveFormat == int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument)
        {
            document.Application.ActiveDocument.SaveAsref 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.Closeref missing, ref missing, ref missing);
        wApp.Quitref missing, ref missing, ref missing);

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

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

        GC.Collect);
   }

    /// <summary>
    /// 打开word模板和word文件
    /// </summary>
    /// <param name=”fileName”>文件名称(模板所在路径)</param>
    /// <param name=”document”></param>
    /// <param name=”application”></param>
    private void OpenWordDocumentstring 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.Openref 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.GetDocPathurl).value;
        iffileurl!=”)
            document.getElementById’FramerControl1′).Openfileurl, 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_Loadobject sender, EventArgs e)
    {
        AjaxPro.Utility.RegisterTypeForAjaxtypeofWordReport_WordView));
        if !IsPostBack)
        {
            string id = HttpContext.Current.Request[“ID”];
            SetWordPrintContentid);
        }
    }

    private void SetWordPrintContentstring itemID)
    {
        ClsWordFactory factory = new ClsWordFactory);
       string docUrl= factory.CreateWordClsWordFactory.WordModelEnum.eProjectZJQualityFlow, itemID);

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

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

最终效果图:



Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注