zoukankan      html  css  js  c++  java
  • C# :Word 标签替代文字或图片 (图片浮于文字之上 插入后回车或换行符替换的解决方法)

    错误类型:“系统找不到 Microsoft.Office.Interop.Word"_或找不到文件或程序集名称“Interop.Microsoft.Office.Interop.Excel

     

    解决方法:在控制面板修复或重装office .

     //------------------------------------------------------------------------------------------------

    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 System.Reflection;
    using Microsoft.Office.Interop.Word;
    using System.Drawing;
    using System.IO;   

    /// <summary>
    /// OutputWod 的摘要说明
    /// </summary>
    public class OutputWod
    {

        
    public OutputWod()
        {
            
    //
            
    // TODO: 在此处添加构造函数逻辑
            
    //
        }

        
    /// <summary>
        
    /// 替换word文档中的logo图片及其它  :替代前,需要在文档的logo创建 书签名:网站标志
        
    /// </summary>
        
    /// <param name="strName">线路名称</param>
        
    /// <param name="filePath">物理路径</param>
        
    /// <param name="filename">文档名称doc</param>
        
    /// <param name="filename">logo路径</param>  
        
    /// <returns></returns>
        public static void CreatWordDocument(string strName, string filePath, string filename, string pic)
        {      
            
    object Nothing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Application app 
    = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document doc 
    = new Microsoft.Office.Interop.Word.Document();
            
    object Obj_FileName = filePath;
            
    object Visible = false;
            
    object ReadOnly = false;
            
    object missing = System.Reflection.Missing.Value;
            
    string strKey = "^p^p";      //要搜索的换行符  --参见code替代段 - 换行符的说明。
            try
            {
                
    //打开文件
                doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
                    
    ref missing, ref missing, ref missing, ref missing,
                    
    ref missing, ref missing, ref missing, ref Visible,
                    
    ref missing, ref missing, ref missing,
                    
    ref missing);
                doc.Activate();

                
    //--判断logo图片是否存在·不存在则略过插入。
                if (File.Exists(System.Web.HttpContext.Current.Server.MapPath(".." + pic)))
                {
                    
    foreach (Microsoft.Office.Interop.Word.Bookmark bm in doc.Bookmarks)
                    {
                        
    if (bm.Name == "网站标志")
                        {
                            bm.Select();

                            
    //要插入的图片文件
                            app.Selection.InlineShapes.AddPicture(System.Web.HttpContext.Current.Server.MapPath(".." + pic), ref missing, ref missing, ref missing);
                            
    //doc.Application.ActiveDocument.InlineShapes[1].Width = 100f; // 图片宽度 
                            
    //doc.Application.ActiveDocument.InlineShapes[1].Height = 8f; // 图片高度

                            
    //将图片设置为四周环绕型
                            Microsoft.Office.Interop.Word.Shape cShape = doc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
                            cShape.WrapFormat.Type 
    = Microsoft.Office.Interop.Word.WdWrapType.wdWrapTopBottom;
                            
    //cShape.Width = 8f;
                            
    //cShape.Height = 100f;
                            cShape.Left = -999998f;
                            cShape.Top 
    = -999999f;// WdShapePosition.wdShapeCenter;居中
                            
    //cShape.WrapFormat.AllowOverlap = 0;
                            
    //cShape.LayoutInCell = 0;
                            
    //cShape.WrapFormat.Side = WdWrapSideType.wdWrapBoth;
                            
    //cShape.RelativeHorizontalPosition = WdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage;
                            
    //cShape.RelativeVerticalPosition = WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;

                            //设置图片浮于文字之上 - 查阅WdWrapType的相关WdWrapType Enumeration
                    cShape.WrapFormat.Type= WdWrapType.wdWrapNone;

     

     

     
                    ////--图片载剪的高度及宽度
                    //cShape.PictureFormat.CropLeft = 2.8f;
                    //cShape.PictureFormat.CropRight = 2.8f;

                    ////--图片显示高比例和宽比例  -缩放比例
                    //cShape.ScaleHeight(1.00f, Microsoft.Office.Core.MsoTriState.msoCTrue, Microsoft.Office.Core.MsoScaleFrom.msoScaleFromMiddle);
                    //cShape.ScaleWidth(1.00f, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoScaleFrom.msoScaleFromMiddle);

     

                            bm.Range.Text = "";
                            
    //doc.Content.Find.Text = strKey;  //调用查找 回车符标记
     
                            
    //清除原logo后,即时删除word文档已存在的回车符。
                            /*用替换法删除多余的空行 
                            如果是段落结束符产生的空行,可以在查找内容中输入^p^p,如果是换行符产生的空行,则在查找内容中输入^l^l。接着在替换为框中输入^p。 
                            解释:^p是段落标记的查找符,^l是换行符,即只进行换行,但未结束段落。
    */
                            
    int i = 0, iCount = 0;
                           
    // Microsoft.Office.Interop.Word.Find wfnd;
                            
    //每次取一部分文档进行判断,符合条件就结束本次搜索,就可以避免每次搜索整个文档了。模型中的Paragraphs对象 可实现要求
                            if (doc.Paragraphs != null && doc.Paragraphs.Count > 5)
                            {
                                iCount 
    = doc.Paragraphs.Count;
                                
    for (i = 1; i <= 5; i++)
                                {
                                    doc.Content.Find.Text 
    = strKey;
                                    
    object FindText, ReplaceWith, Replace;// 
                                    object MissingValue = Type.Missing;
                                    FindText 
    = strKey;//要查找的文本
                                    ReplaceWith = "^p";//替换文本
                                    Replace = Word.WdReplace.wdReplaceOne;
                                    
    /*wdReplaceAll - 替换找到的所有项。
                                     *wdReplaceNone - 不替换找到的任何项。
                                     * wdReplaceOne - 替换找到的第一项。
    */
                                    doc.Content.Find.ClearFormatting();
    //移除Find的搜索文本和段落格式设置
                                    doc.Content.Find.Execute(ref FindText, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref ReplaceWith, ref Replace, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue);
           
                                }                            
                            }
                            
    //结束退出
                            ////break;
                        }                 
                       
                    }
                }
                
    //注意,如果是打开一个HTML文档,而由HTML另存为doc文档时,插入的图片会生成ab.file这样的目录,来存储当前图片文件,如果是新建的空word文档,再把HTML导入到word文档中,再插入图片就不会出现ab.file这样的目录,图片会直接保存的word文档ab.doc中

                
    object sdoc = System.Web.HttpContext.Current.Server.MapPath("../doc/" + strName + "_logo.doc");
                doc.SaveAs(
    ref sdoc, 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);

                
            }
            
    catch(Exception mage)
            {
                
    //写入系统日志
                /*暂略*/
            }
            
    finally
            {

                
    /*--- C# 读写Word :提示将 Word 用作自动化服务器时提示保存 Normal.dot (解决方案之1)   ----*/
                
    /////使用 Quit 方法的 SaveChanges 参数,如下所示: 
                
    ////object SaveOption, OriginalFormat, RouteDocument;
                
    ////SaveOption = Word.WdSaveOptions.wdPromptToSaveChanges;
                
    ////OriginalFormat = Word.WdOriginalFormat.wdPromptUser;
                
    ////RouteDocument = Missing.Value;
                
    ////if (wa != null)
                
    ////{
                
    ////    wa.Quit(ref SaveOption, ref OriginalFormat, ref RouteDocument);
                
    ////    wa = null;
                
    ////}

                
    /*--- C# 读写Word :提示将 Word 用作自动化服务器时提示保存 Normal.dot (解决方案之2)   ----*/
                
    ///// wdApp2.Quit 方法的调用语句之前,添加以下行:
                app.NormalTemplate.Saved = true;


                
    //关闭网页doc
                doc.Close(ref Nothing, ref Nothing, ref Nothing);
                
    if (doc != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
                    doc 
    = null;
                }
                
    //关闭wordApp
                app.Quit(ref Nothing, ref Nothing, ref Nothing);
                
    if (app != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                    app 
    = null;
                }
                
    //释放word进程
                GC.Collect();
            }
        }

        
    ///<summary>
        
    /// 在word 中查找一个字符串直接替换所需要的文本
        
    /// </summary>
        
    /// <param name="strOldText">原文本</param>
        
    /// <param name="strNewText">新文本</param>
        
    /// <returns></returns>
        public static bool FindReplace(Microsoft.Office.Interop.Word.Document oDoc, string strOldText, string strNewText)
        {
            oDoc.Content.Find.Text 
    = strOldText;
            
    object FindText, ReplaceWith, Replace;// 
            object MissingValue = Type.Missing;
            FindText 
    = strOldText;//要查找的文本
            ReplaceWith = strNewText;//替换文本
            Replace = Word.WdReplace.wdReplaceAll;/**//*wdReplaceAll - 替换找到的所有项。
                                                          * wdReplaceNone - 不替换找到的任何项。
                                                        * wdReplaceOne - 替换找到的第一项。
                                                        * 
    */
            oDoc.Content.Find.ClearFormatting();
    //移除Find的搜索文本和段落格式设置
            if (oDoc.Content.Find.Execute(
                
    ref FindText, ref MissingValue,
                
    ref MissingValue, ref MissingValue,
                
    ref MissingValue, ref MissingValue,
                
    ref MissingValue, ref MissingValue, ref MissingValue,
                
    ref ReplaceWith, ref Replace,
                
    ref MissingValue, ref MissingValue,
                
    ref MissingValue, ref MissingValue))
            {
                
    return true;
            }
            
    return false;

        }

        
    //***********生成高质量的缩略图*************
        /// <summary>
        
    /// 生成高质量的缩略图
        
    /// </summary>
        
    /// <param name="originalImagePath">源图路径(物理路径)</param>
        
    /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        
    /// <param name="width">缩略图宽度</param>
        
    /// <param name="height">缩略图高度</param>
        
    /// <param name="mode">生成缩略图的方式</param>    
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {

            System.Drawing.Image originalImage 
    = System.Drawing.Image.FromFile(originalImagePath);

            
    int towidth = width;
            
    int toheight = height;

            
    int x = 0;
            
    int y = 0;
            
    int ow = originalImage.Width;
            
    int oh = originalImage.Height;

            
    switch (mode)
            {
                
    case "HW"://指定高宽缩放(可能变形)                
                    break;
                
    case "W"://指定宽,高按比例                    
                    toheight = originalImage.Height * width / originalImage.Width;
                    
    break;
                
    case "H"://指定高,宽按比例
                    towidth = originalImage.Width * height / originalImage.Height;
                    
    break;
                
    case "Cut"://指定高宽裁减(不变形)                
                    if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                    {
                        oh 
    = originalImage.Height;
                        ow 
    = originalImage.Height * towidth / toheight;
                        y 
    = 0;
                        x 
    = (originalImage.Width - ow) / 2;
                    }
                    
    else
                    {
                        ow 
    = originalImage.Width;
                        oh 
    = originalImage.Width * height / towidth;
                        x 
    = 0;
                        y 
    = (originalImage.Height - oh) / 2;
                    }
                    
    break;
                
    default:
                    
    break;
            }

            
    //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            
    //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            
    //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            
    //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            
    //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            
    //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, new System.Drawing.Rectangle(00, towidth, toheight),
                
    new System.Drawing.Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            
    try
            {
                
    //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            
    catch (System.Exception e)
            {
                
    throw e;
            }
            
    finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        
    //******************结束。



    }

  • 相关阅读:
    Android SDK镜像的介绍使用
    如何在使用MAMP环境下安装MySQLdb
    MySQL – 导出数据成csv
    CSV
    自己写的一个Yeoman的Generator-Require-Angularjs
    笔记
    PHP
    Intellij IDEA 14的注册机
    nodejs
    Python
  • 原文地址:https://www.cnblogs.com/Fooo/p/1506242.html
Copyright © 2011-2022 走看看