1、添加引用
引入Microsoft.Office.Interop.Word
2、设置属性
将属性嵌入互操作类型改为false
3、using 引用
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
4、导出word文档 内容操作
直接复制即可导出简单的示例
成功导出word文档之后就可以修改你想要导出的内容了
object path; //文件路径变量
string strContent; //文本内容变量
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量
path = AppDomain.CurrentDomain.BaseDirectory + "测试" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".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 行间距与缩进、文本字体、字号
wordApp.Selection.ParagraphFormat.LineSpacing = 16f;//设置文档的行间距
wordApp.Selection.ParagraphFormat.FirstLineIndent = 0;//首行缩进的长度
//写入普通文本
strContent = "居中文本\n";
wordDoc.Paragraphs.Last.Range.Font.Size = 22;
wordDoc.Paragraphs.Last.Range.Font.Name = "方正小标宋简体";
wordDoc.Paragraphs.Last.Range.Text = strContent;
wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
object unite = MSWord.WdUnits.wdStory;
wordApp.Selection.EndKey(ref unite, ref Nothing);//将光标移到文本末尾
wordApp.Selection.ParagraphFormat.FirstLineIndent = 10;//设置首行缩进的长度
strContent = "一、项目名称:开工项目\n";
wordDoc.Paragraphs.Last.Range.Font.Name = "仿宋";
wordDoc.Paragraphs.Last.Range.Font.Size = 16;
wordDoc.Paragraphs.Last.Range.Text = strContent;
#endregion
wordApp.Selection.EndKey(ref unite, ref Nothing); //将光标移动到文档末尾
//WdSaveFormat为Word 2003文档的保存格式
object format = MSWord.WdSaveFormat.wdFormatDocument;// office 2007就是wdFormatDocumentDefault
//将wordDoc文档对象的内容保存为DOCX文档
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);
4、导出word常用文本操作
注:设置本行文本首行缩进时,要写在光标移到文本末尾厚后面 否则会影响到上一行的缩进。
设置 | 代码 |
---|---|
文本内容 | wordDoc.Paragraphs.Last.Range.Text=“内容” |
文本字体 | wordDoc.Paragraphs.Last.Range.Font.Name = “仿宋” |
文本大小 | wordDoc.Paragraphs.Last.Range.Font.Size = 16 |
光标移到文本末尾 | wordApp.Selection.EndKey(ref unite, ref Nothing) |
设置首行缩进的长度 | wordApp.Selection.ParagraphFormat.FirstLineIndent = 10 |
文本加粗 | wordDoc.Paragraphs.Last.Range.Font.Bold = 1 |
斜体文本 | wordDoc.Paragraphs.Last.Range.Font.Italic = 1 |
颜色文本 | wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlue(蓝色) |
下划线文本 | wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick |