C#读取和写入Word

来源:互联网 发布:python黑帽子中文网盘 编辑:程序博客网 时间:2024/05/18 23:26
读取word文档得使用com组件:Microsoft Word 15.0 object library
由于office的本不同,组件的版本也会不同,我电脑上装的office2013,所以版本是15.0
Microsoft Word 11.0 object library对应Office2003
Microsoft Word 12.0 object library对应Office2007
Microsoft Word 14.0 object library对应Office2010
Microsoft Word 15.0 object library对应Office2013
使用该组件提供的类和方法来读取Word文档

首先在项目中添加com引用:

然后可以用Microsoft.Office.Interop.Wrod.Application来访问word文档

待读取Word内容如下:


读取Word代码如下:

    private void btnReadWord_Click(object sender, RoutedEventArgs e)        {            //Word.ApplicationClass doc = new Microsoft.Office.Interop.Word.ApplicationClass();                            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();                 Microsoft.Office.Interop.Word.Document doc = null;                 object unknow = Type.Missing;                 app.Visible = true;               string str = @"E:\TEMP\霍少峰开题报告.doc";                 object file = str;                 doc = app.Documents.Open(ref file,                     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, ref unknow);                 //读取第几段内容(空白行、各级标题等均作为一段来算)               string strParaghaph = doc.Paragraphs[4].Range.Text.Trim();               tbParagraph.Text = strParaghaph;               //读取第几句内容(空白行、各级标题等都作为一句来算)               string strSentence = doc.Sentences[5].Text;               tbSentence.Text = strSentence;               //读取整篇内容               string strContent = doc.Content.Text;               tbContent.Text = strContent;              }


创建并写入Word代码如下:

 private void btnWriteWord_Click(object sender, RoutedEventArgs e)        {            string strResult = "";            Object Nothing = System.Reflection.Missing.Value;            Directory.CreateDirectory(@"E:\TEMP\SaveWord");  //创建文件所在目录            string wordName = "MyNewWord" + DateTime.Now.ToLongDateString() + ".doc";//文件名            object wordPathName = @"E:\TEMP\SaveWord\" + wordName;  //文件保存路径            //创建Word文档            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();            Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);            //添加页眉            WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;            WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;            WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[在此添加页眉]");            WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//设置居中            WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置            WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距            //移动焦点并换行            object count = 14;            object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行;            WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点            WordApp.Selection.TypeParagraph();//插入段落            //文档中创建表格            Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 15, 3, ref Nothing, ref Nothing);            //设置表格样式            newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;            newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;            newTable.Columns[1].Width = 100f;            newTable.Columns[2].Width = 220f;            newTable.Columns[3].Width = 105f;            //填充表格内容            newTable.Cell(1, 1).Range.Text = "表头名字哈哈";            newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体            newTable.Cell(1, 1).Range.Font.ColorIndex = (Microsoft.Office.Interop.Word.WdColorIndex)10;            //合并单元格            newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));            WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中            WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中            //填充表格内容            newTable.Cell(2, 1).Range.Text = "Cell(2,1)信息";            newTable.Cell(2, 1).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色            //合并单元格            newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));            WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;            //填充表格内容            newTable.Cell(3, 1).Range.Text = "品牌名称:";            newTable.Cell(3, 2).Range.Text = "BrandName";            newTable.Cell(4, 1).Range.Text = "第4行,第1列";            newTable.Cell(2, 1).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkRed;            newTable.Cell(4, 3).Range.Text = "第4行,第3列";            //纵向合并单元格            newTable.Cell(5, 3).Select();//选中第5行,第3列            object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine;            object moveCount = 4;//合并4列            object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;            WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);            WordApp.Selection.Cells.Merge();            //插入图片            string imageName = @"E:\TEMP\goBUPT3.png";//图片所在路径            object LinkToFile = false;            object SaveWithDocument = true;            object Anchor = WordDoc.Application.Selection.Range;            WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(imageName, ref LinkToFile, ref SaveWithDocument, ref Anchor);            WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度            WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度            //将图片设置为四周环绕型            Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();            s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;            newTable.Cell(12, 1).Range.Text = "(12,1)---(12,3)";            newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));                        //在表格中增加行,所以最终为16行            WordDoc.Content.Tables[1].Rows.Add(ref Nothing);            WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString()+"   By---Jumfens";//“落款”            WordDoc.Paragraphs.Last.Range.Font.ColorIndex =(Microsoft.Office.Interop.Word.WdColorIndex)10;            WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;            //WordDoc.Paragraphs.Last.Range.Text = "\n\n\n\n";//此处会将落款覆盖            WordDoc.Paragraphs.Add(ref Nothing);//在最后再增加一段            WordDoc.Paragraphs.Last.Range.Text = "\n\n";            WordDoc.Paragraphs.Add(ref Nothing);//在最后再增加一段            WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;            string strText = @"    本系统就是针对环境星数据,对经过检验的标准处理流程进行系统化开发,"+                           "并可以使用处理过后的数据生成一些初级地表参数产品。编写这份测试分析报告的"+                           "目的是为了让本系统的用户通过本报告更加信任本系统,测试分析报告主要是对"+                          "软件系统的测试分析工作进行总结与整理。本报告的主要读者是将要使用本系统"+                            "或者需要对环境星进行处理并生产植被指数标准产品的用户。";            WordDoc.Paragraphs.Last.Range.Text = strText;            WordDoc.Paragraphs.Last.Range.Font.ColorIndex = (Microsoft.Office.Interop.Word.WdColorIndex)2;            WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;            WordDoc.Paragraphs.Add(ref Nothing);            WordDoc.Paragraphs.Last.Range.Text = "\n\n\n";                       //文件保存            object objWordName = wordPathName;            WordDoc.SaveAs(ref objWordName, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);            WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);            WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);            strResult = wordName +"\n"+ @"文档生成并写入成功"+"\n"+"信息:"+wordPathName;            MessageBox.Show(strResult);        }


读取效果如下:



写入Word效果如下:


完!




0 0
原创粉丝点击