按照客户的需求,需要用ASP.NET实现生成WORD和PDF文件,现把实现过程写下来,以供以后参考。

      一.配置生成WORD开发运行环境:    

         1. 部署服务器必须操作系统安装为windows2003

         2. 部署服务器必须安装Office Word 2007

         3. 服务器必须设置组件服务 Microsoft Office word

      4.打开组件服务

      5.设置标志属性页为下列用户,用户为administrator

      6.设置安全属性页为自定义,加上NetWork Service用户,加上全部权限

      7.完整代码:

 

using System;
using System.Diagnostics;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Office.Interop.Word;
using System.IO;


using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Epower.ITSM.SqlDAL;
using Epower.DevBase.BaseTools;

namespace Epower.ITSM.Web.Common
{
    public class DataToWord
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="path"></param>
        /// <param name="pathdest"></param>
        public static void WordSaveAs(string path, string pathdest)
        {
            File.Copy(path, pathdest, true);
        }

        #region 生成Word
        /// <summary>
        ///
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="strFileID"></param>
        /// <param name="lngflowmodelid"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static bool CreateWord(string filePath,string strFileID, long lngflowmodelid,DataTable dt)
        {
            _Document WordDoc = null;
            Object oMissing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word._Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            WordApp.Visible = true;
            object filename = filePath;
            try
            {
               WordDoc = WordApp.Documents.Open(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

               //替换模板中的书签,生成内容
               if (WordApp.ActiveDocument.Bookmarks.Exists("flowname"))     //流程名称
               {
                   object oBookMark = "flowname";
                   WordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = dt.Rows[0]["flowname"].ToString();
               }
               if (WordApp.ActiveDocument.Bookmarks.Exists("flowDes"))     //流程描述
               {
                   object oBookMark = "flowDes";
                   WordDoc.Bookmarks.get_Item(ref oBookMark).Range.Text = dt.Rows[0]["Remark"].ToString();
               }

               if (WordApp.ActiveDocument.Bookmarks.Exists("flowlist"))   //流程列表
               {
                   object oContent = "flowlist";
                   Microsoft.Office.Interop.Word.Range startRange = WordApp.ActiveDocument.Bookmarks.get_Item(ref oContent).Range;  //取得位置
                 
                   CreateTable(lngflowmodelid, WordDoc, startRange, ref oMissing);
               }

                //流程图形
               if (WordApp.ActiveDocument.Bookmarks.Exists("flowimage"))
               {
                   object oPreMoney = "flowimage";
                   if (dt.Rows[0]["CHARTS"] != null)
                   {
                       System.IO.MemoryStream ms = new System.IO.MemoryStream((byte[])dt.Rows[0]["CHARTS"]);
                       System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                       //System.Drawing.Image img = System.Drawing.Image.FromFile(sfile);
                       string strFileCatalog = CommonDP.GetConfigValue("TempCataLog", "FileCataLog");
                       string pictureFileName = strFileCatalog + @"\" + oPreMoney + DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Millisecond;
                       img.Save(pictureFileName, System.Drawing.Imaging.ImageFormat.Emf);
                       //img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                       //string pictureFileName = @"c:\km.jpg";
                       object LinkToFile = false;
                       object SaveWithDocument = true;
                       object orange = WordApp.ActiveDocument.Bookmarks.get_Item(ref oPreMoney).Range; //取得位置;
                       WordDoc.InlineShapes.Application.ActiveDocument.InlineShapes.AddPicture(pictureFileName, ref LinkToFile, ref SaveWithDocument, ref orange);

                       //图片宽度
                       WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 420f;
                       //图片高度
                       WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 380f;
                       //将图片设置为四周环绕型
                       //Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
                       //s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;    

                       if (File.Exists(pictureFileName))
                       {
                           File.Delete(pictureFileName);
                       }
                   }
               }

                //保存
                WordDoc.Save();

                WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                return true;
            }
            catch (Exception e)
            {
                WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
                throw e;
            }
            finally
            {
              
            }
        }
        #endregion

        #region 生成流程列表
        /// <summary>
        ///
        /// </summary>
        /// <param name="lngFlowModeID"></param>
        /// <param name="WordDoc"></param>
        /// <param name="startRange"></param>
        /// <param name="oMissing"></param>
        private static void CreateTable(long lngFlowModeID, Microsoft.Office.Interop.Word._Document WordDoc, Microsoft.Office.Interop.Word.Range startRange, ref Object oMissing)
        {
             DataTable dt = App_CheckFlowModelDP.GetFlowNodeModelInfo(lngFlowModeID);

            Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(startRange, dt.Rows.Count + 1,
               4, ref oMissing, ref oMissing);
            newTable.Spacing = 0;
            newTable.TopPadding = 0;
            //为表格划线
            startRange.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle = WdLineStyle.wdLineStyleSingle;
            startRange.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle = WdLineStyle.wdLineStyleSingle;
            startRange.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle = WdLineStyle.wdLineStyleSingle;
            startRange.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleSingle;
            startRange.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = WdLineStyle.wdLineStyleSingle;
            startRange.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle = WdLineStyle.wdLineStyleSingle;

            newTable.Cell(1, 1).Range.Text = "序号";
            newTable.Cell(1, 2).Range.Text = "环节名称";
            //newTable.Cell(1, 3).Range.Text = "环节权限";
            newTable.Cell(1, 3).Range.Text = "时限";
            newTable.Cell(1, 4).Range.Text = "描述";

            object LinkToFile = false;
            object SaveWithDocument = true;

            newTable.Rows[1].Range.Shading.BackgroundPatternColor = WdColor.wdColorPaleBlue;

            int RowCount = 2;
            foreach (DataRow dr in dt.Rows)     //流程列表
            {
                //Hashtable htbRights= EpowerCom.FlowModel.GetNodeSpecRights20090610(lngFlowModeID, long.Parse(dr["NodeModelID"].ToString()));
                //string strRights = string.Empty;
                //for (int i = 0; i < htbRights.Count; i++)
                //{
                //    strRights += "|" + htbRights[i].ToString();
                //}
                newTable.Cell(RowCount, 1).Range.Text = dr["NodeSort"].ToString().Trim();    //序号
                newTable.Cell(RowCount, 2).Range.Text = dr["NodeName"].ToString().Trim();    //环节名称
                //newTable.Cell(RowCount, 3).Range.Text = strRights;                           //权限
                newTable.Cell(RowCount, 3).Range.Text = dr["TotalHours"].ToString().Trim();  //时限
                newTable.Cell(RowCount, 4).Range.Text = dr["Remark"].ToString().Trim();    //描述
                RowCount++;
            }
        }
        #endregion
    }
}

     8.调用代码: 

/// <summary>
        /// 导出文档
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnword_Click(object sender, EventArgs e)
        {
            CreateDoc();
        }

        /// <summary>
        ///
        /// </summary>
        private void CreateDoc()
        {
            long lngFlowModelID = long.Parse(Request.QueryString["FlowModelID"]);
            DataTable dt = App_CheckFlowModelDP.GetFlowModelInfo(lngFlowModelID);    //取得流程模型信息

            if (dt.Rows.Count <= 0)   //没有数据
            {
                PageTool.MsgBox(this, "没有流程相关数据,不能生成文档!");
                return;
            }

            string strFileCatalog = CommonDP.GetConfigValue("TempCataLog", "FileCataLog");
            Random rnd = new Random();
            int n = int.Parse(Request.QueryString["FlowModelID"]);
            string lngFileID = n.ToString();
            string filepath = strFileCatalog + "WordFile";
            if (!Directory.Exists(filepath))
            {
                Directory.CreateDirectory(filepath);//报价单主文件夹
            }

            string strcopypath = Server.MapPath("../ExcelTemplate/wordtemplet.doc");
           
            Epower.ITSM.Web.Common.DataToWord.WordSaveAs(strcopypath, filepath + @"\" + lngFileID);   //模板另存文件


            bool breturn = Epower.ITSM.Web.Common.DataToWord.CreateWord(filepath + @"\" + lngFileID, lngFileID, lngFlowModelID, dt);    //生成文档

           

            string sousPath = String.Format(filepath + "\\{0}}", lngFileID);
            string filename = dt.Rows[0]["FlowName"].ToString() + "流程文档.doc";
            FileDown(sousPath, filename);


            //删除临时文件
            if (File.Exists(filepath + @"\" + lngFileID))
            {
                File.Delete(filepath + @"\" + lngFileID);
            }
        }

        #region 文件下载
        /// <summary>
        ///
        /// </summary>
        /// <param name="sousPath"></param>
        /// <param name="FileName"></param>
        private void FileDown(string sousPath, string FileName)
        {
            if (File.Exists(sousPath))
            {
                System.IO.FileInfo file = new FileInfo(sousPath);
                Response.Clear();
                Response.ClearHeaders();

                //add by 郭亮 2009/08/10  解决部分长中文文件名下载被截断的BUG
                System.Text.Encoding code = System.Text.Encoding.GetEncoding("gb2312");
                Response.ContentEncoding = code;
                Response.HeaderEncoding = code;
                // 如果是其它环境,以上代码去掉

                // 屏蔽此代码 郭亮 2009/08/10  解决部分长中文文件名下载被截断的BUG  如果其它环境,此代码恢复
                //filename = HttpUtility.UrlEncode(filename);

                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=\"" + FileName + "\"");
                Response.AddHeader("Content-Length", file.Length.ToString());
                Response.Flush();
                Response.WriteFile(file.FullName);
                Response.End();
            }
            else
            {
                Response.Write("<script>alert('附件所对应的物理文件已经在应用程序外被删除!')</script>");
                Response.Write("<script>window.history.back()</script>");
            }
        }
        #endregion

 

posted on 2011-08-31 14:26  朱明春  阅读(1258)  评论(0编辑  收藏  举报