C#通过Microsoft.Office.Interop.Word操作Word

C#通过Microsoft.Office.Interop.Word操作Word
1、安装
可以通过NuGet搜索Office,安装Microsoft.Office.Interop.Word;⽐如我的机器是Office2019,没有对应的Microsoft.Office.Interop.Word,则可以通过Nuget⽅式进⾏安装。
2、具体代码操作,到,但实际测试页眉部分会出问题,注释掉就可以了。转载如下:
创建Word;
插⼊⽂字,选择⽂字,编辑⽂字的字号、粗细、颜⾊、下划线等;
设置段落的⾸⾏缩进、⾏距;
设置页⾯页边距和纸张⼤⼩;
设置页眉、页码
插⼊图⽚,设置图⽚宽⾼以及给图⽚添加标题;
插⼊表格,格式化表格,往表格中插⼊数据;
保存Word,打印Word;
重新打开Word等。
Visual studio版本:Visual Studio 2012(2010应该也可以)
准备⼯作:
/*
1. 添加引⽤COM⾥⾯的 Microsoft Word 1
2.0 Object. Library 引⽤(12.0表⽰Word 2007版本)
2. 导命名空间
using MSWord =Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
3. 把引⽤中的Microsoft.Office.Interop.Word的“属性”中的嵌⼊互操作设为False
*/
以下是全部代码:(代码有点长,但请不要有压⼒,直接复制进去就能直接成功运⾏)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
可控硅焊机
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
namespace WindowsFormsCom
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
object path;                              //⽂件路径变量
string strContent;                        //⽂本内容变量
MSWord.Application wordApp;                  //Word应⽤程序变量
MSWord.Document wordDoc;                  //Word⽂档变量
path = Path.GetFullPath("../../") + "\\MyWord_Print.doc";
wordApp = new MSWord.ApplicationClass(); //初始化
wordApp.Visible = true;//使⽂档可见
//如果已存在,则删除
if (File.Exists((string)path))
{
File.Delete((string)path);
}
//由于使⽤的是COM库,因此有许多变量需要⽤Missing.Value代替
Object Nothing = Missing.Value;
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
#region页⾯设置、页眉图⽚和⽂字设置,最后跳出页眉设置
//页⾯设置
wordDoc.PageSetup.PaperSize = MSWord.WdPaperSize.wdPaperA4;//设置纸张样式为A4纸
wordDoc.PageSetup.Orientation = MSWord.WdOrientation.wdOrientPortrait;//排列⽅式为垂直⽅向
wordDoc.PageSetup.TopMargin = 57.0f;
wordDoc.PageSetup.BottomMargin = 57.0f;
wordDoc.PageSetup.LeftMargin = 57.0f;
wordDoc.PageSetup.RightMargin = 57.0f;
wordDoc.PageSetup.HeaderDistance = 30.0f;//页眉位置
#endregion
#region页码设置并添加页码
//为当前页添加页码
MSWord.PageNumbers pns = wordApp.Selection.Sections[1].Headers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;//获取当前页的号码            pns.NumberStyle = MSWord.WdPageNumberStyle.wdPageNumberStyleNumberInDash;//设置页码的风格,是Dash形还是圆形的
pns.HeadingLevelForChapter = 0;
pns.IncludeChapterNumber = false;
pns.RestartNumberingAtSection = false;
pns.StartingNumber = 0; //开始页页码?
object pagenmbetal = MSWord.WdPageNumberAlignment.wdAlignPageNumberCenter;//将号码设置在中间
object first = true;
wordApp.Selection.Sections[1].Footers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first);
#endregion
#region⾏间距与缩进、⽂本字体、字号、加粗、斜体、颜⾊、下划线、下划线颜⾊设置
wordApp.Selection.ParagraphFormat.LineSpacing = 16f;//设置⽂档的⾏间距
wordApp.Selection.ParagraphFormat.FirstLineIndent = 30;//⾸⾏缩进的长度
//写⼊普通⽂本
strContent = "我是普通⽂本\n";
wordDoc.Paragraphs.Last.Range.Text = strContent;
wordDoc.Paragraphs.Last.Range.Text = "我再加⼀⾏试试,这⾥不加'\\n'";
//直接添加段,不是覆盖( += )
wordDoc.Paragraphs.Last.Range.Text += "不会覆盖的,";
//添加在此段的⽂字后⾯,不是新段落
wordDoc.Paragraphs.Last.Range.InsertAfter("这是后⾯的内容\n");
//将⽂档的前4个字替换成"哥是替换⽂字",并将其颜⾊设为红⾊
object start = 0;
object end = 4;
MSWord.Range rang = wordDoc.Range(ref start, ref end);
rang.Font.Color = MSWord.WdColor.wdColorRed;
rang.Text = "哥是替换⽂字";
wordDoc.Range(ref start, ref end);
//写⼊⿊体⽂本
object unite = MSWord.WdUnits.wdStory;
wordApp.Selection.EndKey(ref unite, ref Nothing);//将光标移到⽂本末尾
wordApp.Selection.ParagraphFormat.FirstLineIndent = 0;//取消⾸⾏缩进的长度
strContent = "这是⿊体⽂本\n";
wordDoc.Paragraphs.Last.Range.Font.Name = "⿊体";
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写⼊加粗⽂本
strContent = "这是粗体⽂本\n"; //
wordApp.Selection.EndKey(ref unite, ref Nothing);//这⼀句不加,有时候好像也不出问题,不过还是加了安全
wordDoc.Paragraphs.Last.Range.Font.Bold = 1;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写⼊15号字体⽂本
strContent = "我这个⽂本的字号是15号,⽽且是宋体\n";
wordApp.Selection.EndKey(ref unite, ref Nothing);
wordDoc.Paragraphs.Last.Range.Font.Size = 15;
wordDoc.Paragraphs.Last.Range.Font.Name = "宋体";
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写⼊斜体⽂本
strContent = "我是斜体字⽂本\n";
wordApp.Selection.EndKey(ref unite, ref Nothing);
wordDoc.Paragraphs.Last.Range.Font.Italic = 1;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写⼊蓝⾊⽂本rj45防水接头
strContent = "我是蓝⾊的⽂本\n";
wordApp.Selection.EndKey(ref unite, ref Nothing);
wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlue;
wordDoc.Paragraphs.Last.Range.Text = strContent;
/
/写⼊下划线⽂本
strContent = "我是下划线⽂本\n";
wordApp.Selection.EndKey(ref unite, ref Nothing);
wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick;
wordDoc.Paragraphs.Last.Range.Text = strContent;
//写⼊红⾊下画线⽂本
strContent = "我是点线下划线,并且下划线是红⾊的\n";
wordApp.Selection.EndKey(ref unite, ref Nothing);
wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineDottedHeavy;
wordDoc.Paragraphs.Last.Range.Font.UnderlineColor = MSWord.WdColor.wdColorRed;
wordDoc.Paragraphs.Last.Range.Text = strContent;
/
/取消下划线,并且将字号调整为12号
strContent = "我他妈不要下划线了,并且设置字号为12号,⿊⾊不要斜体\n";
wordApp.Selection.EndKey(ref unite, ref Nothing);
wordDoc.Paragraphs.Last.Range.Font.Size = 12;
wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineNone;
wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlack;
wordDoc.Paragraphs.Last.Range.Font.Italic = 0;
wordDoc.Paragraphs.Last.Range.Text = strContent;
#endregion
#region插⼊图⽚、居中显⽰,设置图⽚的绝对尺⼨和缩放尺⼨,并给图⽚添加标题
wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到⽂档末尾
/
/图⽚⽂件的路径
string filename = Path.GetFullPath("../../") + "\\6.jpg";
//要向Word⽂档中插⼊图⽚的位置
Object range = wordDoc.Paragraphs.Last.Range;
//定义该插⼊的图⽚是否为外部链接
Object linkToFile = false;              //默认,这⾥貌似设置为bool类型更清晰⼀些
//定义要插⼊的图⽚是否随Word⽂档⼀起保存
Object saveWithDocument = true;              //默认
//使⽤InlineShapes.AddPicture⽅法(【即“嵌⼊型”】)插⼊图⽚
wordDoc.InlineShapes.AddPicture(filename, ref linkToFile, ref saveWithDocument, ref range);
wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//居中显⽰图⽚
//设置图⽚宽⾼的绝对⼤⼩
//wordDoc.InlineShapes[1].Width = 200;
//wordDoc.InlineShapes[1].Height = 150;
//按⽐例缩放⼤⼩
wordDoc.InlineShapes[1].ScaleWidth = 20;//缩⼩到20% ?
wordDoc.InlineShapes[1].ScaleHeight = 20;
//在图下⽅居中添加图⽚标题
wordDoc.Content.InsertAfter("\n");//这⼀句与下⼀句的顺序不能颠倒,原因还没搞透
wordApp.Selection.EndKey(ref unite, ref Nothing);
wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
wordApp.Selection.Font.Size = 10;//字体⼤⼩
wordApp.Selection.TypeText("图1 测试图⽚\n");
#endregion
#region添加表格、填充数据、设置表格⾏列宽⾼、合并单元格、添加表头斜线、给单元格添加图⽚
wordDoc.Content.InsertAfter("\n");//这⼀句与下⼀句的顺序不能颠倒,原因还没搞透
wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到⽂档末尾
wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
//object WdLine2 = MSWord.WdUnits.wdLine;//换⼀⾏;
//wordApp.Selection.MoveDown(ref WdLine2, 6, ref Nothing);//向下跨15⾏输⼊表格,这样表格就在⽂字下⽅了,不过这是⾮主流的⽅法            //设置表格的⾏数和列数
int tableRow = 6;
int tableColumn = 6;
//定义⼀个Word中的表格对象
MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range,
tableRow, tableColumn, ref Nothing, ref Nothing);
//默认创建的表格没有边框,这⾥修改其属性,使得创建的表格带有边框
table.Borders.Enable = 1;//这个值可以设置得很⼤,例如5、13等等
//表格的索引是从1开始的。
wordDoc.Tables[1].Cell(1, 1).Range.Text = "列\n⾏";
for (int i = 1; i < tableRow; i++)
{
for (int j = 1; j < tableColumn; j++)
{
if (i == 1)
{
table.Cell(i, j + 1).Range.Text = "Column " + j;//填充每列的标题
}
if (j == 1)
{
table.Cell(i + 1, j).Range.Text = "Row " + i; //填充每⾏的标题
}
table.Cell(i + 1, j + 1).Range.Text = i + "⾏ " + j + "列";  //填充表格的各个⼩格⼦
}
}
/
/添加⾏
table.Rows.Add(ref Nothing);
table.Rows[tableRow + 1].Height = 35;//设置新增加的这⾏表格的⾼度
//向新添加的⾏的单元格中添加图⽚
string FileName = Path.GetFullPath("../../") + "\\6.jpg";//图⽚所在路径
object LinkToFile = false;
object SaveWithDocument = true;
object Anchor = table.Cell(tableRow + 1, tableColumn).Range;//选中要添加图⽚的单元格
wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
//由于是本⽂档的第2张图,所以这⾥是InlineShapes[2]
wordDoc.Application.ActiveDocument.InlineShapes[2].Width = 50;//图⽚宽度
wordDoc.Application.ActiveDocument.InlineShapes[2].Height = 35;//图⽚⾼度
// 将图⽚设置为四周环绕型
MSWord.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[2].ConvertToShape();
s.WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare;
//设置table样式
table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;//⾼度规则是:⾏⾼有最低值下限?
table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));//
table.Range.Font.Size = 10.5F;
table.Range.Font.Bold = 0;
table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//表格⽂本居中
table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom;//⽂本垂直贴到底部
//设置table边框样式
table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;//表格外框是双线
table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;//表格内框是单线
table.Rows[1].Range.Font.Bold = 1;//加粗
table.Rows[1].Range.Font.Size = 12F;
table.Cell(1, 1).Range.Font.Size = 10.5F;
wordApp.Selection.Cells.Height = 30;//所有单元格的⾼度
//除第⼀⾏外,其他⾏的⾏⾼都设置为20
for (int i = 2; i <= tableRow; i++)
{
table.Rows[i].Height = 20;
}
//将表格左上⾓的单元格⾥的⽂字(“⾏” 和 “列”)居右
table.Cell(1, 1).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;
//将表格左上⾓的单元格⾥⾯下⾯的“列”字移到左边,相⽐上⼀⾏就是将ParagraphFormat改成了Paragraphs[2].Format
table.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;
table.Columns[1].Width = 50;//将第 1列宽度设置为50
//将其他列的宽度都设置为75
for (int i = 2; i <= tableColumn; i++)
{
table.Columns[i].Width = 75;
}
帷幕灌浆
//添加表头斜线,并设置表头的样式
table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Visible = true;
table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Color = MSWord.WdColor.wdColorRed;
table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].LineWidth = MSWord.WdLineWidth.wdLineWidth150pt;
//合并单元格
table.Cell(4, 4).Merge(table.Cell(4, 5));//横向合并
table.Cell(2, 3).Merge(table.Cell(4, 3));//纵向合并,合并(2,3),(3,3),(4,3)
#endregion
wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到⽂档末尾
wordDoc.Content.InsertAfter("\n");
wordDoc.Content.InsertAfter("就写这么多,算了吧!2016.09.27");
//WdSaveFormat为Word 2003⽂档的保存格式
object format = MSWord.WdSaveFormat.wdFormatDocument;// office 2007就是wdFormatDocumentDefault
//将wordDoc⽂档对象的内容保存为doc⽂档
wordDoc.SaveAs(ref path, ref format, 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⽂档对象
/
/看是不是要打印
隔热杯
//wordDoc.PrintOut();
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭wordApp组件对象
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
//Console.WriteLine(path + " 创建完毕!");
//Console.ReadKey();
//我还要打开这个⽂档玩玩
MSWord.Application app = new MSWord.Application();
MSWord.Document doc = null;
try
betal
芯模
{
object unknow = Type.Missing;
app.Visible = true;
string str = Path.GetFullPath("../../") + "\\MyWord_Print.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 temp = doc.Paragraphs[1].Range.Text.Trim();
/
/Console.WriteLine("输出temp⼲嘛?");
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
wordDoc = doc;
wordDoc.Paragraphs.Last.Range.Text += "我真的不打算再写了,就写这么多吧";
}
private void Form1_Load(object sender, EventArgs e)
{
/
/label1.Text = Path.GetFullPath("../../");
}
}
}
⽣成编辑的Word内容如下图所⽰:

本文发布于:2024-09-21 16:21:29,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/3/349095.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:设置   表格   添加   页码   页眉   缩进
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议