C#生成Word笔记

    换了新公司,换了新环境,旧公司倒闭,新公司开始不能上网,突然觉得什么不好的事都让我遇上了...当然,这些和题目一点关系都没有..
    新公司的一个项目,刚开始分析发现需要使用C#生成Word文档,由于以前没有这方面的经验,所以要在项目还没有开始之前,先试探一下怎么使用.由于下面这个类的代码是东找西找的,所以也不做什么解释,只是加了一些注释而以!在此做个笔记而以!

 public class WordHelp
    {
        /// <SUMMARY></SUMMARY>  
        /// word 应用对象  
        ///   
        private Microsoft.Office.Interop.Word.Application _wordApplication;

        /// <SUMMARY></SUMMARY>  
        /// word 文件对象  
        ///   
        private Microsoft.Office.Interop.Word.Document _wordDocument;
        /// <summary>
        /// 文件名称(全路径)
        /// </summary>
        private string _fileName;

        /// <summary>
        /// 空对象
        /// </summary>
        private object missing = System.Reflection.Missing.Value;

        #region 构造函数
        /// <summary>
        /// 初始化word应用对象
        /// </summary>
        public WordHelp()
        {
            this._wordApplication = new Microsoft.Office.Interop.Word.ApplicationClass();
            Object myNothing = System.Reflection.Missing.Value;
            this._wordDocument = this._wordApplication.Documents.Add(ref myNothing, ref myNothing, ref myNothing, ref myNothing);
        }
        /// <summary>
        /// 初始化word应用对象,同时指定文件
        /// </summary>
        /// <param name="fileName"></param>
        public WordHelp(string fileName)
        {
            _fileName = fileName;

            this._wordApplication = new Microsoft.Office.Interop.Word.ApplicationClass();
            object nullobj = System.Reflection.Missing.Value;
            object fileobj = fileName;
            this._wordDocument = _wordApplication.Documents.Open(ref fileobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj,
                ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj
                );
        }
        #endregion

        #region 保存文件
        /// <SUMMARY></SUMMARY>  
        /// 保存文件 
        /// <PARAM name="pFileName" />保存的文件名  
        public void SaveWord(string pFileName)
        {
            object myFileName = pFileName;
            object myWordFormatDocument = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
            object myLockd = false;
            object myPassword = "";
            object myAddto = true;
            try
            {
                this._wordDocument.SaveAs(ref myFileName, ref myWordFormatDocument, ref myLockd, ref myPassword, ref myAddto, ref myPassword,
                ref myLockd, ref myLockd, ref myLockd, ref myLockd, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing);
            }
            catch
            {
                throw new Exception("导出word文档失败!");
            }
        }
        /// <SUMMARY></SUMMARY>  
        /// 保存文件 
        ///
        public void SaveWord()
        {
            object myFileName = _fileName;
            object myWordFormatDocument = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
            object myLockd = false;
            object myPassword = "";
            object myAddto = true;
            try
            {
                this._wordDocument.SaveAs(ref myFileName, ref myWordFormatDocument, ref myLockd, ref myPassword, ref myAddto, ref myPassword,
                ref myLockd, ref myLockd, ref myLockd, ref myLockd, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing);
            }
            catch
            {
                throw new Exception("导出word文档失败!");
            }
        }
        #endregion

        /// <summary>
        /// 文档的"页面设置"属性
        /// </summary>
        public void SetPageStyle()
        {
            _wordApplication.ActiveDocument.PageSetup.LineNumbering.Active = 0;//行编号
            _wordApplication.ActiveDocument.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;//页面方向
            _wordApplication.ActiveDocument.PageSetup.TopMargin = _wordApplication.CentimetersToPoints(float.Parse("2.54"));//上页边距
            _wordApplication.ActiveDocument.PageSetup.BottomMargin = _wordApplication.CentimetersToPoints(float.Parse("2.54"));//下页边距
            _wordApplication.ActiveDocument.PageSetup.LeftMargin = _wordApplication.CentimetersToPoints(float.Parse("3.17"));//左页边距
            _wordApplication.ActiveDocument.PageSetup.RightMargin = _wordApplication.CentimetersToPoints(float.Parse("3.17"));//右页边距
            _wordApplication.ActiveDocument.PageSetup.Gutter = _wordApplication.CentimetersToPoints(float.Parse("0"));//装订线位置
            _wordApplication.ActiveDocument.PageSetup.HeaderDistance = _wordApplication.CentimetersToPoints(float.Parse("1.5"));//页眉
            _wordApplication.ActiveDocument.PageSetup.FooterDistance = _wordApplication.CentimetersToPoints(float.Parse("1.75"));//页脚
            _wordApplication.ActiveDocument.PageSetup.PageWidth = _wordApplication.CentimetersToPoints(float.Parse("21"));//纸张宽度
            _wordApplication.ActiveDocument.PageSetup.PageHeight = _wordApplication.CentimetersToPoints(float.Parse("29.7"));//纸张高度
            _wordApplication.ActiveDocument.PageSetup.FirstPageTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源
            _wordApplication.ActiveDocument.PageSetup.OtherPagesTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源
            _wordApplication.ActiveDocument.PageSetup.SectionStart = Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage;//节的起始位置:新建页
            _wordApplication.ActiveDocument.PageSetup.OddAndEvenPagesHeaderFooter = 0;//页眉页脚-奇偶页不同
            _wordApplication.ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = 0;//页眉页脚-首页不同
            _wordApplication.ActiveDocument.PageSetup.VerticalAlignment = Microsoft.Office.Interop.Word.WdVerticalAlignment.wdAlignVerticalTop;//页面垂直对齐方式
            _wordApplication.ActiveDocument.PageSetup.SuppressEndnotes = 0;//不隐藏尾注
            _wordApplication.ActiveDocument.PageSetup.MirrorMargins = 0;//不设置首页的内外边距
            _wordApplication.ActiveDocument.PageSetup.TwoPagesOnOne = false;//不双面打印
            _wordApplication.ActiveDocument.PageSetup.BookFoldPrinting = false;//不设置手动双面正面打印
            _wordApplication.ActiveDocument.PageSetup.BookFoldRevPrinting = false;//不设置手动双面背面打印
            _wordApplication.ActiveDocument.PageSetup.BookFoldPrintingSheets = 1;//打印默认份数
            _wordApplication.ActiveDocument.PageSetup.GutterPos = Microsoft.Office.Interop.Word.WdGutterStyle.wdGutterPosLeft;//装订线位于左侧
            _wordApplication.ActiveDocument.PageSetup.LinesPage = 40;//默认页行数量
            _wordApplication.ActiveDocument.PageSetup.LayoutMode = Microsoft.Office.Interop.Word.WdLayoutMode.wdLayoutModeLineGrid;//版式模式为“只指定行网格”
        }

        /// <summary>
        /// 添加文字
        /// </summary>
        /// <param name="text"></param>
        public void AddText(string text, int pFontSize, Microsoft.Office.Interop.Word.WdColor pFontColor, int pFontBold, Microsoft.Office.Interop.Word.WdParagraphAlignment ptextAlignment, string fontName)
        {
            //加粗
            if (pFontBold >= 1)
            {
                _wordApplication.Selection.Font.Bold = 1;
            }
            else
            {
                _wordApplication.Selection.Font.Bold = 0;
            }
            //对齐方式
            _wordApplication.Selection.ParagraphFormat.Alignment = ptextAlignment;
            //文字大小
            _wordApplication.Selection.Font.Size = (float)pFontSize;
            //文字字体
            _wordApplication.Selection.Font.Name = fontName;
            //文字颜色
            _wordApplication.Selection.Font.Color = pFontColor;
            //还有很多,可以根据vs的智能提示慢慢看

            _wordApplication.Selection.TypeText(text);
        }
        /// <summary>
        /// 添加文字
        /// </summary>
        /// <param name="text"></param>
        public void AddText(string text, bool isNewLine)
        {
            if (isNewLine)
            {
                text += "\r\n";
            }
            _wordApplication.Selection.TypeText(text);
        }
        /// <summary>
        /// 添加超链
        /// </summary>
        /// <param name="url"></param>
        /// <param name="text"></param>
        public void AddLink(string url, string text)
        {
            object objtext = text;
            object refstring = (object)url;

            _wordApplication.ActiveDocument.Hyperlinks.Add(_wordApplication.Selection.Range, ref refstring, ref objtext, ref objtext, ref objtext, ref objtext);
        }

        /// <summary>
        /// 添加图片
        /// </summary>
        /// <param name="pic"></param>
        public void AddPrice(string pic, Microsoft.Office.Interop.Word.WdParagraphAlignment align)
        {
            _wordApplication.Selection.ParagraphFormat.Alignment = align;
            _wordApplication.Selection.InlineShapes.AddPicture(pic, ref missing, ref missing, ref missing);
        }

        /// <summary>
        /// 移动光标
        /// </summary>
        /// <param name="count"></param>
        public void MoveDown(int count)
        {
            object objCount = count;
            _wordApplication.Selection.MoveDown(ref missing, ref objCount, ref missing);
        }
        /// <summary>
        /// 添加表格
        /// </summary>
        public void AddTable()
        {
            _wordApplication.ActiveDocument.Tables.Add(_wordApplication.Selection.Range, 2, 2, ref missing, ref missing);
            _wordApplication.Selection.TypeText("aaaaaa");
            object objCount = 1;
            _wordApplication.Selection.MoveRight(ref missing, ref objCount, ref missing);
            _wordApplication.Selection.TypeText("bbbb");
            MoveDown(2);
        }

        /// <summary>
        /// 添加标签
        /// </summary>
        /// <param name="bookMark"></param>
        public void AddBookMark(string bookMark)
        {
            Microsoft.Office.Interop.Word.Range rng = _wordDocument.Content;
            int lenght = _wordDocument.Characters.Count - 1;
            object start = lenght;
            object end = lenght;
            rng = _wordDocument.Range(ref start, ref end);
            object range = rng;
            _wordDocument.Bookmarks.Add(bookMark, ref range);
        }
        /// <summary>
        /// 定位到书签
        /// </summary>
        /// <param name="strBookMarkName"></param>
        public void GotoBookMark(string strBookMarkName)
        {
            object Bookmark = (int)Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;
            object NameBookMark = strBookMarkName;
            _wordApplication.Selection.GoTo(ref Bookmark, ref missing, ref missing, ref NameBookMark);
        }

        /// <summary>
        /// 换行
        /// </summary>
        public void NewLine()
        {
            _wordApplication.Selection.TypeParagraph();
        }
        /// <summary>
        /// 插入分页符
        /// </summary>
        public void NewPage()
        {
            Microsoft.Office.Interop.Word.Paragraph para;
            para = _wordDocument.Content.Paragraphs.Add(ref missing);
            object pBreak = (int)WdBreakType.wdSectionBreakNextPage;
            para.Range.InsertBreak(ref pBreak);
        }

        /// <summary>
        /// 释放对象
        /// </summary>
        public void Close()
        {
            _wordDocument.Close(ref missing, ref missing, ref missing);
        }

        /// <summary>
        /// 插入图形
        /// </summary>
        /// <param name="isSelectShape">接下的内容是否要显示在绘图中</param>
        public void AddShape()
        {
            _wordApplication.ActiveDocument.Shapes.AddShape(1, 70, 170, 140, 120, ref  missing).Select(ref missing);
            _wordApplication.Selection.ShapeRange.Fill.ForeColor.RGB = 2551530;//填充颜色
            _wordApplication.Selection.ShapeRange.Line.ForeColor.RGB = 153510;//边框颜色
            _wordApplication.Selection.ShapeRange.TextFrame.TextRange.Select();
        }
    }


注意:如果是插入绘图的话,可以在绘图之前,先插入一个标签AddBookMark(),然后画完图之后再定位到之前插入的标签那里GotoBookMark(),继续写入你需要的内容.当然,你有更好的方法可以和我分享.
 
其实做到后面,发现根本不用怎么在网上找代码的,只需要使用word里面的宏,录制你要生成的一些操作,然后再查看宏的代码,里面就会自动帮你生成VB代码,根据这些VB代码转换成相应的C#代码,相信应该不是什么难事吧!

posted on 2010-08-22 21:02  Ss_Andy  阅读(2316)  评论(0编辑  收藏  举报