本文中用C#来操作Word,包括:
创建Word;
插入文字,选择文字,编辑文字的字号、粗细、颜色、下划线等;
设置段落的首行缩进、行距;
设置页面页边距和纸张大小;
设置页眉、页码;
插入图片,设置图片宽高以及给图片添加标题;
插入表格,格式化表格,往表格中插入数据;
保存Word,打印Word;
重新打开Word等。
Visual studio版本:Visual Studio 2012(2010应该也可以)
准备工作:
/*
1. 添加引用COM里面的 Microsoft Word 12.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.Linq;
using System.Runtime.InteropServices;
using System.Text;
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
namespace Console_WordSkill_All
{
class Program
{
static void Main(string[] args)
{
object path; //文件路径变量
string strContent; //文本内容变量
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量
path = Environment.CurrentDirectory + "\\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;//页眉位置
//设置页眉
wordApp.ActiveWindow.View.Type = MSWord.WdViewType.wdNormalView;//普通视图(即页面视图)样式
wordApp.ActiveWindow.View.SeekView = MSWord.WdSeekView.wdSeekPrimaryHeader;//进入页眉设置,其中页眉边距在页面设置中已完成
wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;//页眉中的文字右对齐
//插入页眉图片(测试结果图片未插入成功)
wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
string headerfile = @"C:\Users\xiahui\Desktop\OficeProgram\3.jpg";
MSWord.InlineShape shape1 = wordApp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref Nothing, ref Nothing, ref Nothing);
shape1.Height = 5;//强行设置貌似无效,图片没有按设置的缩放——图片的比例并没有改变。
shape1.Width = 20;
wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(" 文档页眉");//在页眉的图片后面追