.net Word Develop

    最近公司接了一个制作流程图的项目,起初是准备用Excel输出,大家就开始做前期的准备,后来流程图也用Excel画出来了,公司又要求用Word输入,于是继续研究,好在之前从网上找了一个真对于vba和.net操作Excel的文档,个人感觉比较权威,所以开发Excel的时候如鱼得水,转换成Word的时候,个人认为都是微软的东西,大概都是差不多的。结果发现很多方法都很相似,但是用起来有些差异,有的时候调用的方法都是一样的,但是显示的结果却大为不同,以下是我这几天对Word研究的总结,拿出来和大家分享一下。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
using System.Web;

 

namespace NameSpace
{
    /// <summary>
    /// Word操作类
    /// </summary>
    public class WordBebindCode
    {
        private Word.Application thisApplication = null;
        private Word.Document thisDocument = null;

        private Object oMissing = System.Reflection.Missing.Value;

        /// <summary>
        /// Application object.
        /// </summary>
        private Word.Application ThisApplication
        {
            get { return thisApplication; }
        }

        /// <summary>
        /// Document object.
        /// </summary>
        private Word.Document ThisDocument
        {
            get { return thisDocument; }
        }


        /// <summary>
        /// 构造函数
        /// </summary>
        public WordBebindCode()
  {
             thisApplication = new Word.Application();
             thisDocument = thisApplication.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
  }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="filePath">Word文件路径</param>
        public WordBebindCode(string filePath)
        {
            thisApplication = new Word.Application();
            Object fileName = @filePath;
            thisDocument = thisApplication.Documents.Add(ref fileName, ref oMissing, ref oMissing, ref oMissing);
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="wordDoc">Word文档对象</param>
        /// <param name="wordApplication">Word应用对象</param>
        public WordBebindCode(Word.Document wordDoc, Word.Application wordApplication)
        {
            thisApplication = wordApplication;
            thisDocument = wordDoc;
        }

        /// <summary>
        /// 回车
        /// </summary>
        public void InserSentence()
        {
            Word.Selection sln = ThisApplication.Selection;
            sln.TypeParagraph();
        }

        /// <summary>
        /// 在光标处输入文字
        /// </summary>
        /// <param name="text">要输入的文字</param>
        public void InsertTextAtSelection(string text)
        {
            Word.Selection sln = ThisApplication.Selection;
            sln.TypeText(text);
        }

        /// <summary>
        /// 将文字作为图形显示在页面上
        /// </summary>
        /// <param name="text">文字</param>
        /// <param name="x">图形的X坐标</param>
        /// <param name="y">图形Y坐标</param>
        public void InsertTextAsShape(string text, float x, float y)
        {
            ThisDocument.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1, text, "宋体", 10, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, x, y, ref oMissing);
        }

        /// <summary>
        /// 画线
        /// </summary>
        /// <param name="beginX">起点X坐标</param>
        /// <param name="beginY">起点Y坐标</param>
        /// <param name="endX">终点X坐标</param>
        /// <param name="endY">重点Y坐标</param>
        /// <param name="existEndArrowhead">是否显示指示箭头</param>
        /// <returns>返回画线对象</returns>
        public Word.Shape DrawLine(float beginX, float beginY, float endX, float endY, bool existEndArrowhead)
        {
            Word.Shape line = thisDocument.Shapes.AddLine(beginX, beginY, endX, endY, ref oMissing);
            if (existEndArrowhead)
            {
                line.Line.EndArrowheadStyle = Microsoft.Office.Core.MsoArrowheadStyle.msoArrowheadTriangle;
            }

            return line;
        }

        /// <summary>
        /// 画虚线
        /// </summary>
        /// <param name="beginX">起点X坐标</param>
        /// <param name="beginY">起点Y坐标</param>
        /// <param name="endX">终点X坐标</param>
        /// <param name="endY">重点Y坐标</param>
        /// <param name="existEndArrowhead">是否显示指示箭头</param>
        /// <returns>返回画线对象</returns>
        public Word.Shape DrawDashLine(float beginX, float beginY, float endX, float endY, bool existEndArrowhead)
        {
            Word.Shape line = thisDocument.Shapes.AddLine(beginX, beginY, endX, endY, ref oMissing);
            line.Line.DashStyle = Microsoft.Office.Core.MsoLineDashStyle.msoLineDash;
            if (existEndArrowhead)
            {
                line.Line.EndArrowheadStyle = Microsoft.Office.Core.MsoArrowheadStyle.msoArrowheadTriangle;
            }

            return line;
        }

        /// <summary>
        /// 画矩形
        /// </summary>
        /// <param name="text">文字</param>
        // <param name="beginX">图形X坐标</param>
        /// <param name="beginY">图形Y坐标</param>
        /// <param name="endX">图形宽度</param>
        /// <param name="endY">图形高度</param>
        /// <returns>矩形对象</returns>
        public Word.Shape DrawRectangle(string text, float leftX, float leftY, float width, float height)
        {
            Word.Shape rectShape = thisDocument.Shapes.AddShape((int)Office.MsoAutoShapeType.msoShapeRectangle, leftX, leftY, width, height, ref oMissing);
            rectShape.TextFrame.TextRange.Text = text;
            rectShape.TextFrame.TextRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;

            return rectShape;
        }

      

        /// <summary>
        /// 保存文档到指定的地方
        /// </summary>
        public void SaveDocument()
        {
            // Save the active document
            ThisDocument.Save();
            // or
            ThisApplication.ActiveDocument.Save();
        }


        /// <summary>
        /// 关闭Word进程
        /// </summary>
        public void Close()
        {
            Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
            Object originalFormat = Type.Missing;
            Object routeDocument = Type.Missing;
            ThisApplication.Documents.Close(ref saveChanges, ref originalFormat, ref routeDocument);

            ThisApplication.Quit(ref saveChanges, ref originalFormat, ref routeDocument);


            Marshal.FinalReleaseComObject(ThisDocument);
            Marshal.FinalReleaseComObject(ThisApplication);

            GC.Collect();
        }


        /// <summary>
        /// 清楚服务器上存留的Word进程
        /// </summary>
        public static void KillWordProcess()
        {
            Process[] processes = Process.GetProcessesByName("WINWORD");

            foreach (Process pro in processes)
            {
                pro.Kill();
            }
        }


        /// <summary>
        ///  将Word通过Web输出
        /// </summary>
        /// <param name="response">HttpResponse</param>
        public void OutputWord(HttpResponse response)
        {
            StringBuilder sBuilder = new StringBuilder(new Random().Next(1, 100000).ToString());

            string fName = sBuilder.Append(".doc").ToString();
            try
            {
                string excelPath = System.Web.HttpContext.Current.Server.MapPath(@"~/WordTempFiles/");
                bool existDirectory = Directory.Exists(excelPath);

                if (!existDirectory)
                {
                    Directory.CreateDirectory(excelPath);
                }

                StringBuilder fileFullName = new StringBuilder(excelPath);
                fName = fileFullName.Append(fName).ToString();

                File.Delete(fName);
                SaveAs(fName);
            }
            finally
            {
                Close();
            }

            response.ClearContent();
            response.ClearHeaders();
            response.ContentType = "application/msword";
            response.WriteFile(fName);
            response.Flush();
            response.Close();

            File.Delete(fName);

        }

        /// <summary>
        ///  输出Word
        /// </summary>
        /// <param name="response">HttpResponse</param>
        public void OutputToWord(HttpResponse response)
        {
            StringBuilder sBuilder = new StringBuilder(new Random().Next(1, 100000).ToString());

            string fName = sBuilder.Append(".doc").ToString();
            try
            {
                string excelPath = System.Web.HttpContext.Current.Server.MapPath(@"~/WordTempFiles/");
                bool existDirectory = Directory.Exists(excelPath);

                if (!existDirectory)
                {
                    Directory.CreateDirectory(excelPath);
                }

                StringBuilder fileFullName = new StringBuilder(excelPath);
                fName = fileFullName.Append(fName).ToString();

                File.Delete(fName);
                SaveAs(fName);
            }
            finally
            {
                Close();
            }

            System.IO.FileInfo file = new FileInfo(fName);
            response.Clear();
            //response.Charset = "GB2312";
            //response.ContentEncoding = System.Text.Encoding.UTF8;
            response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpContext.Current.Server.UrlEncode(file.Name));
            response.AddHeader("Content-Length", file.Length.ToString());
            response.ContentType = "application/vnd.ms-word";

            response.WriteFile(file.FullName);
            response.Flush();
            response.Close();

            File.Delete(fName);
        }

        /// <summary>
        /// 保存Word文件到服务器(不显示)
        /// </summary>
        public void SaveAs(string filePath)
        {
            // Save the document. In a real application,
            // you'd want to test to see if the file
            // already exists. This will overwrite any previously
            // existing documents.
            Object fileName = @filePath;
            Object fileFormat = Type.Missing;
            Object lockComments = Type.Missing;
            Object password = Type.Missing;
            Object addToRecentFiles = Type.Missing;
            Object writePassword = Type.Missing;
            Object readOnlyRecommended = Type.Missing;
            Object embedTrueTypeFonts = Type.Missing;
            Object saveNativePictureFormat = Type.Missing;
            Object saveFormsData = Type.Missing;
            Object saveAsAOCELetter = Type.Missing;
            Object encoding = Type.Missing;
            Object insertLineBreaks = Type.Missing;
            Object allowSubstitutions = Type.Missing;
            Object lineEnding = Type.Missing;
            Object addBiDiMarks = Type.Missing;

            ThisDocument.SaveAs(ref fileName, ref fileFormat, ref lockComments,
              ref password, ref addToRecentFiles, ref writePassword,
              ref readOnlyRecommended, ref embedTrueTypeFonts, ref saveNativePictureFormat,
              ref saveFormsData, ref saveAsAOCELetter, ref encoding,
              ref insertLineBreaks, ref allowSubstitutions, ref lineEnding,
              ref addBiDiMarks);
        }


    }
}

 

 

其中就InsertTextAsShape方法 在做Excel的时候用的是thisDocument.Shapes.AddLabel 文档上明确表示这个图形只体现汉字,没有文本框,不知道为什么用到Word上就偏偏出了边框,最后想想到把这个边框都设置成Word文档的背景色,后来又发现这些属性都是只读(无语),后来无奈的情况,试探了一下Word的艺术字效果,试了n多枚举,最后老天有眼,微软终于剩下一个和正常字体一样的艺术字。

还有我在做自动连接两个图形的线的时候,发现和Excel相比下,Word在画图的时候需要把图画在画布上才能将两个图形用AddConnector连接,但是好像这个画布必须要激活的的情况下才能连接,后来查了很多资料,老外也没有一个正确的解释,最后只好搁浅,如果有做出来的朋友最好分享一下,先谢了。 以上写的代码本人都经过测试过了,可以借鉴,这些只是实现了Word以下部分功能,希望能起到抛砖引玉的作用,具体的可以参考Msdn.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值