C#操作word,自己的一些整合

来源:互联网 发布:分区表丢失数据恢复 编辑:程序博客网 时间:2024/06/06 18:28

不敢说是完全原创,参考了很多网上大神的代码,自己也只是搬过来调试一下而已。

概述

某项目需要自动生成Word文档,查找了许多资料,发现还是C#实现起来比较容易,也比较灵活。

环境:
Office 2010
Visual Studio 2010
Win10

网上找了很多教程,首先需要设置引用。
1.右击“解决方案资源管理器”中的项目目录下的“引用”,选择“添加引用”,打开“添加引用”对话框
2.在“添加引用”对话框中,选择“COM”>“Microsoft Word 15.0 Object Library”,点击“确定”按钮(这个版本号和本机安装的Word版本有关,2010是15.0)
3.相同操作打开“添加引用”对话框中,选择“浏览”项,查找到”Microsoft.Office.Interop.Word.dll”文件,选中它,点击“确定”按钮。

整个类的代码如下:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.Office.Interop.Word;namespace DocCreator{    class CreateDoc    {        private Microsoft.Office.Interop.Word.Application wordApp = null;        private Document wordDoc = null;        public Application Application        {            get            {                return wordApp;            }            set            {                wordApp = value;            }        }        public Document Document        {            get            {                return wordDoc;            }            set            {                wordDoc= value;            }        }        //通过模板创建新文档        public void CreateNewDocument(string filePath)        {            killWinWordProcess();            wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();            wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;            wordApp.Visible =false;            object missing = System.Reflection.Missing.Value;            object templateName = filePath;            wordDoc = wordApp.Documents.Open(ref templateName,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);        }        //保存新文件        public void SaveDocument(string filePath)        {            object fileName = filePath;            object format = WdSaveFormat.wdFormatDocument;  //保存格式            object miss = System.Reflection.Missing.Value;            wordDoc.SaveAs2(ref fileName,ref format,ref miss, ref miss,ref miss,ref miss,ref miss,                ref miss,ref miss,ref miss,ref miss,ref miss,ref miss,ref miss,ref miss,ref miss,ref miss);            object SaveChanges = WdSaveOptions.wdSaveChanges;            object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat;            object RouteDocument =false;            wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);            wordApp.Quit(ref SaveChanges,ref OriginalFormat,ref RouteDocument);        }        //在书签处插入值        public bool InsertValue(string bookmark,string value)        {            object bkObj =bookmark;            if(wordApp.ActiveDocument.Bookmarks.Exists(bookmark))            {                wordApp.ActiveDocument.Bookmarks[bkObj].Select();                wordApp.Selection.TypeText(value);                return true;            }            return false;        }        //插入表格,bookmark书签        public Table InsertTable(string bookmark, int rows, int columns,float width)        {            object miss =System.Reflection.Missing.Value;            object toStart =bookmark;            Range range =wordDoc.Bookmarks[toStart].Range;//表格插入位置            Table newTable =wordDoc.Tables.Add(range,rows, columns, ref miss, ref miss);            //设置表的格式            newTable.Borders.Enable =1; //允许有边框,默认没有边框(为0时报错,1为实线边框,2、3为虚线边框,以后的数字没试过)            newTable.Borders.OutsideLineWidth=WdLineWidth.wdLineWidth050pt;//边框宽度            if(width != 0)            {                newTable.PreferredWidth=width;//表格宽度            }            newTable.AllowPageBreaks =false;            return newTable;        }        //合并单元格 表名,开始行号,开始列号,结束行号,结束列号        public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1,int row2, int column2)        {            table.Cell(row1,column1).Merge(table.Cell(row2,column2));        }        //设置表格内容对齐方式Align水平方向,Vertical垂直方向(左对齐,居中对齐,右对齐分别对应Align和Vertical的值为-1,0,1)        public void SetParagraph_Table(Microsoft.Office.Interop.Word.Table table, int Align, int Vertical)        {            switch(Align)            {            case -1:table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphLeft;break;//左对齐            case 0: table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphCenter;break;//水平居中            case 1: table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphRight;break;//右对齐            }            switch(Vertical)            {                case -1: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalTop;break;//顶端对齐                case 0: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalCenter;break;//垂直居中                case 1: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalBottom;break;//底端对齐            }        }        //设置表格字体        public void SetFont_Table(Microsoft.Office.Interop.Word.Table table, string fontName, double size)        {            if(size != 0)            {                table.Range.Font.Size =Convert.ToSingle(size);            }            if(fontName !="")            {                table.Range.Font.Name =fontName;            }        }        //是否使用边框,n表格的序号,use是或否        public void UseBorder(int n,bool use)        {            if(use)            {                wordDoc.Content.Tables[n].Borders.Enable =1; //允许有边框,默认没有边框(为0时无边框,1为实线边框,2、3为虚线边框,以后的数字没试过)            }            else            {                wordDoc.Content.Tables[n].Borders.Enable =2; //允许有边框,默认没有边框(为0时无边框,1为实线边框,2、3为虚线边框,以后的数字没试过)            }        }        //给表格插入一行,n表格的序号从1开始记        public void AddRow(int n)        {            object miss =System.Reflection.Missing.Value;            wordDoc.Content.Tables[n].Rows.Add(ref miss);        }        //给表格添加一行        public void AddRow(Microsoft.Office.Interop.Word.Table table)        {            object miss =System.Reflection.Missing.Value;            table.Rows.Add(ref miss);        }        //给表格插入rows行,n为表格的序号        public void AddRow(int n, int rows)        {            object miss =System.Reflection.Missing.Value;            Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];            for(int i = 0; i < rows; i++)            {                table.Rows.Add(ref miss);            }        }        //给表格中单元格插入元素,table所在表格,row行号,column列号,value插入的元素        public void InsertCell(Microsoft.Office.Interop.Word.Table table, int row, int column,string value)        {            table.Cell(row,column).Range.Text =value;        }        //给表格中单元格插入元素,n表格的序号从1开始记,row行号,column列号,value插入的元素        public void InsertCell(int n, int row,int column, string value)        {            wordDoc.Content.Tables[n].Cell(row,column).Range.Text =value;        }        //给表格插入一行数据,n为表格的序号,row行号,columns列数,values插入的值        public void InsertCell(int n, int row,int columns, string[] values)        {            Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];            for(int i = 0; i < columns; i++)            {                table.Cell(row,i + 1).Range.Text =values[i];            }        }        //插入图片        public void InsertPicture(string bookmark, string picturePath, float width, float hight)        {            object miss = System.Reflection.Missing.Value;            object oStart =bookmark;            Object linkToFile =false;    //图片是否为外部链接            Object saveWithDocument =true; //图片是否随文档一起保存            object range =wordDoc.Bookmarks.get_Item(ref oStart).Range;//图片插入位置            wordDoc.InlineShapes.AddPicture(picturePath,ref linkToFile, ref saveWithDocument, ref range);            wordDoc.Application.ActiveDocument.InlineShapes[1].Width=width; //设置图片宽度            wordDoc.Application.ActiveDocument.InlineShapes[1].Height=hight; //设置图片高度        }        //插入一段文字,text为文字内容        public void InsertText(string bookmark, string text)        {            object oStart =bookmark;            object range =wordDoc.Bookmarks.get_Item(ref oStart).Range;            Paragraph wp =wordDoc.Content.Paragraphs.Add(ref range);            wp.Format.SpaceBefore= 6;            wp.Range.Text =text;            wp.Format.SpaceAfter =24;            wp.Range.InsertParagraphAfter();            wordDoc.Paragraphs.Last.Range.Text ="\n";        }        //杀掉winword.exe进程        public void killWinWordProcess()        {            System.Diagnostics.Process[]processes=System.Diagnostics.Process.GetProcessesByName("WINWORD");            foreach (System.Diagnostics.Process process in processes)            {                bool b = process.MainWindowTitle=="";                if (process.MainWindowTitle =="")                {                    process.Kill();                }            }        }    }}using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows.Forms;using Microsoft.Office.Interop.Word;namespace DocCreator{    public class CreateDoc    {        private Microsoft.Office.Interop.Word.Application wordApp = null;        private Document wordDoc = null;        public Microsoft.Office.Interop.Word.Application Application        {            get            {                return wordApp;            }            set            {                wordApp = value;            }        }        public Document Document        {            get            {                return wordDoc;            }            set            {                wordDoc = value;            }        }        //通过模板创建新文档        public void CreateNewDocument(string filePath)        {            killWinWordProcess();            wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();            wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;            wordApp.Visible = false;            object missing = System.Reflection.Missing.Value;            object templateName = filePath;            wordDoc = wordApp.Documents.Open(ref templateName, 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);        }        //保存新文件        public void SaveDocument(string filePath)        {            object fileName = filePath;            object format = WdSaveFormat.wdFormatDocument;  //保存格式            object miss = System.Reflection.Missing.Value;            wordDoc.SaveAs2(ref fileName, ref format, ref miss, ref miss, ref miss, ref miss, ref miss,                            ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);            object SaveChanges = WdSaveOptions.wdSaveChanges;            object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat;            object RouteDocument = false;            wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);            wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);        }        //在书签处插入值        public bool InsertValue(string bookmark, string value)        {            object bkObj = bookmark;            if(wordApp.ActiveDocument.Bookmarks.Exists(bookmark))            {                wordApp.ActiveDocument.Bookmarks[bkObj].Select();                wordApp.Selection.TypeText(value);                return true;            }            return false;        }        //插入表格,bookmark书签        public Table InsertTable(string bookmark, int rows, int columns, float width)        {            object miss = System.Reflection.Missing.Value;            object toStart = bookmark;            Range range = wordDoc.Bookmarks[toStart].Range;//表格插入位置            Table newTable = wordDoc.Tables.Add(range, rows, columns, ref miss, ref miss);            //设置表的格式            newTable.Borders.Enable = 1; //允许有边框,默认没有边框(为0时报错,1为实线边框,2、3为虚线边框,以后的数字没试过)            newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//边框宽度            if(width != 0)            {                newTable.PreferredWidth = width;//表格宽度            }            newTable.AllowPageBreaks = false;            return newTable;        }        //合并单元格 表名,开始行号,开始列号,结束行号,结束列号        public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2)        {            table.Cell(row1, column1).Merge(table.Cell(row2, column2));        }        //设置表格内容对齐方式Align水平方向,Vertical垂直方向(左对齐,居中对齐,右对齐分别对应Align和Vertical的值为-1,0,1)        public void SetParagraph_Table(Microsoft.Office.Interop.Word.Table table, int Align, int Vertical)        {            switch(Align)            {                case -1:                    table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;                    break;//左对齐                case 0:                    table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;                    break;//水平居中                case 1:                    table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;                    break;//右对齐            }            switch(Vertical)            {                case -1:                    table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop;                    break;//顶端对齐                case 0:                    table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;                    break;//垂直居中                case 1:                    table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom;                    break;//底端对齐            }        }        //设置表格字体        public void SetFont_Table(Microsoft.Office.Interop.Word.Table table, string fontName, double size)        {            if(size != 0)            {                table.Range.Font.Size = Convert.ToSingle(size);            }            if(fontName != "")            {                table.Range.Font.Name = fontName;            }        }        //是否使用边框,n表格的序号,use是或否        public void UseBorder(int n, bool use)        {            if(use)            {                wordDoc.Content.Tables[n].Borders.Enable = 1; //允许有边框,默认没有边框(为0时无边框,1为实线边框,2、3为虚线边框,以后的数字没试过)            }            else            {                wordDoc.Content.Tables[n].Borders.Enable = 2; //允许有边框,默认没有边框(为0时无边框,1为实线边框,2、3为虚线边框,以后的数字没试过)            }        }        //给表格插入一行,n表格的序号从1开始记        public void AddRow(int n)        {            object miss = System.Reflection.Missing.Value;            wordDoc.Content.Tables[n].Rows.Add(ref miss);        }        //给表格添加一行        public void AddRow(Microsoft.Office.Interop.Word.Table table)        {            object miss = System.Reflection.Missing.Value;            table.Rows.Add(ref miss);        }        //给表格插入rows行,n为表格的序号        public void AddRow(int n, int rows)        {            object miss = System.Reflection.Missing.Value;            Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];            for(int i = 0; i < rows; i++)            {                table.Rows.Add(ref miss);            }        }        //给表格中单元格插入元素,table所在表格,row行号,column列号,value插入的元素        public void InsertCell(Microsoft.Office.Interop.Word.Table table, int row, int column, string value)        {            table.Cell(row, column).Range.Text = value;        }        //给表格中单元格插入元素,n表格的序号从1开始记,row行号,column列号,value插入的元素        public void InsertCell(int n, int row, int column, string value)        {            wordDoc.Content.Tables[n].Cell(row, column).Range.Text = value;        }        //给表格插入一行数据,n为表格的序号,row行号,columns列数,values插入的值        public void InsertCell(int n, int row, int columns, string[] values)        {            Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];            for(int i = 0; i < columns; i++)            {                table.Cell(row, i + 1).Range.Text = values[i];            }        }        //插入图片        public void InsertPicture(string bookmark, string picturePath, float width, float hight)        {            object miss = System.Reflection.Missing.Value;            object oStart = bookmark;            Object linkToFile = false;    //图片是否为外部链接            Object saveWithDocument = true; //图片是否随文档一起保存            object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//图片插入位置            wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);            wordDoc.Application.ActiveDocument.InlineShapes[1].Width = width; //设置图片宽度            wordDoc.Application.ActiveDocument.InlineShapes[1].Height = hight; //设置图片高度        }        //插入一段文字,text为文字内容        public void InsertText(string bookmark, string text)        {            object oStart = bookmark;            object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;            Paragraph wp = wordDoc.Content.Paragraphs.Add(ref range);            wp.Format.SpaceBefore = 6;            wp.Range.Text = text;            wp.Format.SpaceAfter = 24;            wp.Range.InsertParagraphAfter();            wordDoc.Paragraphs.Last.Range.Text = "\n";        }        //杀掉winword.exe进程        public void killWinWordProcess()        {            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");            foreach(System.Diagnostics.Process process in processes)            {                bool b = process.MainWindowTitle == "";                if(process.MainWindowTitle == "")                {                    process.Kill();                }            }        }        //打开文档        public void openFile(object fileName)        {            try            {                if(wordApp.Documents.Count > 0)                {                    if(MessageBox.Show("已经打开了一个word文档,你想重新打开该文档么?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)                    {                        object unknow = Type.Missing;                        wordDoc = wordApp.ActiveDocument;                        if(MessageBox.Show("是否需要保存?", "保存", MessageBoxButtons.YesNo) == DialogResult.Yes)                        {                            wordApp.ActiveDocument.Save();                        }                        wordApp.ActiveDocument.Close(ref unknow, ref unknow, ref unknow);                        wordApp.Visible = false;                    }                    else                    {                        return;                    }                }            }            catch            {                wordApp = new Microsoft.Office.Interop.Word.Application();            }            try            {                object unknow = Type.Missing;                wordApp.Visible = true;                wordDoc = wordApp.Documents.Open(ref fileName, ref unknow, ref unknow, ref unknow, ref unknow                                                 , ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow, ref unknow                                                 , ref unknow);            }            catch(Exception ex)            {                MessageBox.Show("出现错误:" + ex.ToString());            }        }        //读取word文档第几段        public object readPar(int i)        {            try            {                string temp = wordDoc.Paragraphs[i].Range.Text.Trim();                return temp;            }            catch(Exception e)            {                MessageBox.Show("Error:" + e.ToString());                return null;            }        }        //返回一共几段        public int getParCount()        {            return wordDoc.Paragraphs.Count;        }        //关闭文档        public void closeFile()        {            try            {                object unknow = Type.Missing;                object saveChanges = WdSaveOptions.wdPromptToSaveChanges;                wordApp.ActiveDocument.Close(ref saveChanges, ref unknow, ref unknow);            }            catch(Exception ex)            {                MessageBox.Show("Error:" + ex.ToString());            }        }        //关闭word程序        public void quit()        {            try            {                object unknow = Type.Missing;                object saveChanges = WdSaveOptions.wdSaveChanges;                wordApp.Quit(ref saveChanges, ref unknow, ref unknow);            }            catch(Exception)            {            }        }        public void replaceChar()        {            try            {                object replaceAll = WdReplace.wdReplaceAll;                object missing = Type.Missing;                wordApp.Selection.Find.ClearFormatting();                wordApp.Selection.Find.Text = "^l";                wordApp.Selection.Find.Replacement.ClearFormatting();                wordApp.Selection.Find.Replacement.Text = "^p";                wordApp.Selection.Find.Execute(                    ref missing, ref missing, ref missing, ref missing, ref missing,                    ref missing, ref missing, ref missing, ref missing, ref missing,                    ref replaceAll, ref missing, ref missing, ref missing, ref missing);            }            catch(Exception e)            {                MessageBox.Show("文档出现错误,请重新操作");            }        }    }}

经调试,编译器提示ApplicationClass()无法匹配接口,上网搜到解答,发现应该是Word兼容性问题。解决办法是点击解决方案中“引用”,选择Microsoft.Office.Interop.Word,选项中选择“嵌入式互操作类型”,将属性设定成FALSE,问题解决。

使用的话,应该先载入模板

DocCreator docCreator = new DocCreator();docCreator.CreateNewDocument(tmpPath);

在书签处插入一个值

docCreator.InsertValue("Bookmark","value"); //在书签处插入值

创建一个表格

Table table = docCreator.InsertTable("bookMark_table",2,3,0);  //在书签bookmark_table处插入2列3行宽度最大的表

合并单元格

docCreator.MergeCell(table,1,1,1,3);    //表名,开始行号,开始列号,结束行号,结束列号

表格添加一行

docCreator.AddRow(table);

表格添加数据

string[] value= {"ying","yi","de","xi","fa"};docCreator.InsertCell(1,2,5,values);    //给模板中的第一个表格的第二行的5列分别加入数据

插入图片

string picturePath=@"c:\Documents\1.jpg";docCreator.InsertPicture("Bookmark_picture",picturePath,150,150);   //书签位置,图片路径,宽度,高度

插入文字

string text = "I am a test, and I want to make Document!";docCreator.InsertText("Bookmark_text",text);

保存文档

docCreator.InsertText(repPath);
原创粉丝点击