原文1地址:http://www.cnblogs.com/lantionzy/archive/2009/10/23/1588511.html

原文2地址: http://www.cnblogs.com/wucan/p/3806401.html

写代码之前,需要引用对应的DLL文件:

a、Interop.Microsoft.Office.Interop.Word.dll  (网上可以下载)

b、mscorlib.dll  (添加引用--->.NET中即可找到)

1 新建word 文档

/// <summary>
/// 动态生成Word文档并填充内容
/// </summary>
/// <param name="dir">文档目录</param>
/// <param name="fileName">文档名</param>
/// <returns>返回自定义信息</returns>
public static bool CreateWordFile(string dir, string fileName)
{
try
{
Object oMissing = System.Reflection.Missing.Value; if (!Directory.Exists(dir))
{
//创建文件所在目录
Directory.CreateDirectory(dir);
}
//创建Word文档(Microsoft.Office.Interop.Word)
Microsoft.Office.Interop.Word._Application WordApp = new Application();
WordApp.Visible = true;
Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Add(
ref oMissing, ref oMissing, ref oMissing, ref oMissing); //保存
object filename = dir + fileName;
WordDoc.SaveAs(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return false;
}
}

2  给word文档添加页眉页脚

/// <summary>
/// 给word文档添加页眉
/// </summary>
/// <param name="filePath">文件名</param>
/// <returns></returns>
public static bool AddPageHeaderFooter(string filePath)
{
try
{
Object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word._Application WordApp = new Application();
WordApp.Visible = true;
object filename = filePath;
Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Open(ref filename, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); ////添加页眉方法一:
//WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
//WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
//WordApp.ActiveWindow.ActivePane.Selection.InsertAfter( "**公司" );//页眉内容 ////添加页眉方法二:
if (WordApp.ActiveWindow.ActivePane.View.Type == WdViewType.wdNormalView ||
WordApp.ActiveWindow.ActivePane.View.Type == WdViewType.wdOutlineView)
{
WordApp.ActiveWindow.ActivePane.View.Type = WdViewType.wdPrintView;
}
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
WordApp.Selection.HeaderFooter.LinkToPrevious = false;
WordApp.Selection.HeaderFooter.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
WordApp.Selection.HeaderFooter.Range.Text = "页眉内容"; WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageFooter;
WordApp.Selection.HeaderFooter.LinkToPrevious = false;
WordApp.Selection.HeaderFooter.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("页脚内容"); //跳出页眉页脚设置
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; //保存
WordDoc.Save();
WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return false;
}
}

3 设置文档格式并添加文本内容、超链接

/// <summary>
/// 设置文档格式并添加内容
/// </summary>
/// <param name="filePath">文件名</param>
/// <returns></returns>
public static bool AddContent(string filePath)
{
try
{
Object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word._Application WordApp = new Application();
WordApp.Visible = true;
object filename = filePath;
Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Open(ref filename, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //设置居左
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; //设置文档的行间距
WordApp.Selection.ParagraphFormat.LineSpacing = 15f;
//插入段落
//WordApp.Selection.TypeParagraph();
Microsoft.Office.Interop.Word.Paragraph para;
para = WordDoc.Content.Paragraphs.Add(ref oMissing);
//正常格式
para.Range.Text = "This is paragraph 1";
//para.Range.Font.Bold = 2;
//para.Range.Font.Color = WdColor.wdColorRed;
//para.Range.Font.Italic = 2;
para.Range.InsertParagraphAfter(); para.Range.Text = "This is paragraph 2";
para.Range.InsertParagraphAfter(); //插入Hyperlink
Microsoft.Office.Interop.Word.Selection mySelection = WordApp.ActiveWindow.Selection;
mySelection.Start = 9999;
mySelection.End = 9999;
Microsoft.Office.Interop.Word.Range myRange = mySelection.Range; Microsoft.Office.Interop.Word.Hyperlinks myLinks = WordDoc.Hyperlinks;
object linkAddr = @"http://www.cnblogs.com/lantionzy";
Microsoft.Office.Interop.Word.Hyperlink myLink = myLinks.Add(myRange, ref linkAddr,
ref oMissing);
WordApp.ActiveWindow.Selection.InsertAfter("\n"); //落款
WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();
WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; //保存
WordDoc.Save();
WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return false;
}
}

4 添加图片

/// <summary>
/// 文档中添加图片
/// </summary>
/// <param name="filePath">word文件名</param>
/// <param name="picPath">picture文件名</param>
/// <returns></returns>
public static bool AddPicture(string filePath, string picPath)
{
try
{
Object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word._Application WordApp = new Application();
WordApp.Visible = true;
object filename = filePath;
Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Open(ref filename, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //移动光标文档末尾
object count = WordDoc.Paragraphs.Count;
object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdParagraph;
WordApp.Selection.MoveDown(ref WdLine, ref count, ref oMissing);//移动焦点
WordApp.Selection.TypeParagraph();//插入段落 object LinkToFile = false;
object SaveWithDocument = true;
object Anchor = WordDoc.Application.Selection.Range;
WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(picPath, ref LinkToFile, ref SaveWithDocument, ref Anchor); //保存
WordDoc.Save();
WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return false;
}
}

5 表格处理(插入表格、设置格式、填充内容、表格中加图片)

/// <summary>
/// 表格处理
/// </summary>
/// <param name="filePath">word文件名</param>
/// <returns></returns>
public static bool AddTable(string filePath)
{
try
{
Object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word._Application WordApp = new Application();
WordApp.Visible = true;
object filename = filePath;
Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Open(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); //插入表格
Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, , , ref oMissing, ref oMissing);
//设置表格
newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
newTable.Columns[].Width = 100f;
newTable.Columns[].Width = 220f;
newTable.Columns[].Width = 105f; //填充表格内容
newTable.Cell(, ).Range.Text = "我的简历";
//设置单元格中字体为粗体
newTable.Cell(, ).Range.Bold = ; //合并单元格
newTable.Cell(, ).Merge(newTable.Cell(, )); //垂直居中
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
//水平居中
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; //填充表格内容
newTable.Cell(, ).Range.Text = "座右铭:";
//设置单元格内字体颜色
newTable.Cell(, ).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;
//合并单元格
newTable.Cell(, ).Merge(newTable.Cell(, ));
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //填充表格内容
newTable.Cell(, ).Range.Text = "姓名:";
newTable.Cell(, ).Range.Text = "雷鑫";
//纵向合并单元格
newTable.Cell(, ).Select();
//选中一行
object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
object moveCount = ;
object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
WordApp.Selection.Cells.Merge(); //表格中插入图片
string pictureFileName = System.IO.Directory.GetCurrentDirectory() + @"\picture.jpg";
object LinkToFile = false;
object SaveWithDocument = true;
object Anchor = WordDoc.Application.Selection.Range;
WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(pictureFileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
//图片宽度
WordDoc.Application.ActiveDocument.InlineShapes[].Width = 100f;
//图片高度
WordDoc.Application.ActiveDocument.InlineShapes[].Height = 100f;
//将图片设置为四周环绕型
Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[].ConvertToShape();
s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare; newTable.Cell(, ).Range.Text = "备注:";
newTable.Cell(, ).Merge(newTable.Cell(, ));
//在表格中增加行
WordDoc.Content.Tables[].Rows.Add(ref oMissing); //保存
WordDoc.Save();
WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return false;
}
}

6  把Word文档转化为Html文件

/// <summary>
/// 把Word文档转化为Html文件
/// </summary>
/// <param name="wordFileName">word文件名</param>
/// <param name="htmlFileName">要保存的html文件名</param>
/// <returns></returns>
public static bool WordToHtml(string wordFileName, string htmlFileName)
{
try
{
Object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word._Application WordApp = new Application();
WordApp.Visible = true;
object filename = wordFileName;
Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Open(ref filename, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); // Type wordType = WordApp.GetType();
// 打开文件
Type docsType = WordApp.Documents.GetType();
// 转换格式,另存为
Type docType = WordDoc.GetType();
object saveFileName = htmlFileName;
docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, WordDoc,
new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML }); 其它格式: //保存
WordDoc.Save();
WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
return false;
}
}

7  加密、解密、插入分页符

using Microsoft.Office.Interop.Word;
using MSWord = Microsoft.Office.Interop.Word;
using System.Reflection; private void button1_Click(object sender, System.EventArgs e)
{
//Word文档保护密码
string Pass = "ITIS@997168";
object PassWord = Pass;
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量
try
{
object Nothing = Missing.Value; //初始化
wordApp = new MSWord.ApplicationClass(); // 打开已存在的Word
object FileName = @"E:\archive\CMPLatest_2117_230614-1053.Rtf";
object readOnly = false;
object isVisible = true;
object objFalse = false; wordDoc = wordApp.Documents.Open(ref FileName, ref Nothing, ref readOnly, ref Nothing, ref PassWord, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref isVisible, ref Nothing, ref Nothing, ref Nothing, ref Nothing); //激活Word文档
wordDoc.Activate();
//判断是否有密码
if (wordDoc.HasPassword)
{
wordDoc.Password = null;
} //检查是否为Word文档设置保护功能,没有设置保护功能,就解除密码保护
if (wordDoc.ProtectionType != WdProtectionType.wdNoProtection)
{
wordDoc.Unprotect(ref PassWord);
} //跳转到指定书签
object toMark = MSWord.WdGoToItem.wdGoToBookmark;
//分页符
object oPageBreak = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak; //定义书签名称 PartB
object BookMarkName_b = "bmf_b";
wordDoc.ActiveWindow.Selection.GoTo(ref toMark, ref Nothing, ref Nothing, ref BookMarkName_b);
//插入分页符
wordDoc.ActiveWindow.Selection.InsertBreak(ref oPageBreak); //定义书签名称 PartC1
object BookMarkName_c1 = "bmf_c1";
wordDoc.ActiveWindow.Selection.GoTo(ref toMark, ref Nothing, ref Nothing, ref BookMarkName_c1);
//插入分页符
wordDoc.ActiveWindow.Selection.InsertBreak(ref oPageBreak); //定义书签名称 PartC2
object BookMarkName_c2 = "bmf_c2";
wordDoc.ActiveWindow.Selection.GoTo(ref toMark, ref Nothing, ref Nothing, ref BookMarkName_c2);
//插入分页符
wordDoc.ActiveWindow.Selection.InsertBreak(ref oPageBreak); //对Word文档进行加密保护
if(PassWord.ToString() != null)
{
wordDoc.Protect(WdProtectionType.wdAllowOnlyReading, ref objFalse, ref PassWord, ref Nothing, ref Nothing);
} //将插入分页符后的Word文档保存一下
wordDoc.SaveAs(ref FileName, ref Nothing, ref Nothing, ref Nothing, ref objFalse, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref isVisible, ref Nothing, ref Nothing, ref Nothing, ref Nothing); //标记为最终状态,禁止弹出对话框
//wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
//标记为最终状态
//wordDoc.Final = true; //关闭Word文档
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
}
catch(Exception ex)
{ }
}

(转)C#操作Word文档的更多相关文章

  1. iText操作word文档总结

    操作word文档的工具有很多,除了iText之外还有POI,但是POI擅长的功能是操作excel,虽然也可以操作word,但是能力有限,而且还有很多的bug,技术并不成熟,下面就重点介绍一种操作wor ...

  2. C#操作Word文档(加密、解密、对应书签插入分页符)

    原文:C#操作Word文档(加密.解密.对应书签插入分页符) 最近做一个项目,客户要求对已经生成好的RTF文件中的内容进行分页显示,由于之前对这方面没有什么了解,后来在网上也找了相关的资料,并结合自己 ...

  3. 利用Python操作Word文档【图片】

    利用Python操作Word文档

  4. Java文件操作系列[3]——使用jacob操作word文档

    Java对word文档的操作需要通过第三方组件实现,例如jacob.iText.POI和java2word等.jacob组件的功能最强大,可以操作word,Excel等格式的文件.该组件调用的的是操作 ...

  5. QTP操作word文档

    QTP可以对word文档进行操作,这里最主要展示的是向word文档写入内容,并保存的功能. Option explicit Dim wordApp Set wordApp = createobject ...

  6. c#中操作word文档-四、对象模型

    转自:http://blog.csdn.net/ruby97/article/details/7406806 Word对象模型  (.Net Perspective) 本文主要针对在Visual St ...

  7. python 操作word文档

    因为工作需要操作一些word文档,记录一下学习思路 #-*- encoding: utf8 -*- import win32com from win32com.client import Dispat ...

  8. 2.QT中操作word文档

     Qt/Windows桌面版提供了ActiveQt框架,用以为Qt和ActiveX提供完美结合.ActiveQt由两个模块组成: A   QAxContainer模块允许我们使用COM对象并且可以 ...

  9. C# 操作Word 文档——添加Word页眉、页脚和页码

    在Word文档中,我们可以通过添加页眉.页脚的方式来丰富文档内容.添加页眉.页脚时,可以添加时间.日期.文档标题,文档引用信息.页码.内容解释.图片/LOGO等多种图文信息.同时也可根据需要调整文字或 ...

  10. Java操作word文档使用JACOB和POI操作word,Excel,PPT需要的jar包

    可参考文档: http://wibiline.iteye.com/blog/1725492 下载jar包 http://download.csdn.net/download/javashixiaofe ...

随机推荐

  1. Unity 资源的优化管理 学习

  2. 各业务场景下的技术推荐 【.net】

    后端: 1.webapi的token加密:  1)JWT验证算法,不推荐:2)RSA 2.集合的扩展:C5.dll 3.对象映射工具:AutoMapper .TinyMapper 4.任务调度框架:Q ...

  3. day28 1.缓冲区 2.subprocess 3.黏包现象 4.黏包现象解决方案 5.struct

    1.缓冲区: 输入缓冲区  输出缓冲区 2. subprocess的使用import subprocess sub_obj = subprocess.Popen('ls', #系统指令shell=Tr ...

  4. powerdesigner-ER图建模

    PowerDesigner是一款功能非常强大的建模工具软件,足以与Rose比肩,同样是当今最著名的建模软件之一.Rose是专攻UML对象模型的建模工具,之后才向数据库建模发展,而PowerDesign ...

  5. 谈谈在 .Net 平台上的 软件生态 和 软件生产力

    我们可以先看看这篇文章 : <看 StackOverflow 如何用 25 台服务器撑起 5.6 亿的月 PV>    http://www.nowamagic.net/librarys/ ...

  6. 寻找“最好”(4)——不等约束和KKT条件

    不等约束 上篇文章介绍了如何在等式约束下使用拉格朗日乘子法,然而真实的世界哪有那么多等式约束?我们碰到的大多数问题都是不等约束.对于不等约束的优化问题,可以这样描述: 其中f(x)是目标函数,g(x) ...

  7. 【转】OPPO A77保持应用后台运行方法

    原文网址:http://www.3533.com/news/16/201708/163086/1.htm OPPO A77保持应用后台运行方法.手机的运行内存大小有限,因此在出现运行应用过多时,系统就 ...

  8. Redis 基础命令

    1. 进入redis目录,启动redis cd src ./redis-server 2.  进入redis目录,启动redis客户端 cd src ./redis-cli 3. info命令 4. ...

  9. diff命令详解

    Linux diff命令 Linux diff命令用于比较文件的差异. diff以逐行的方式,比较文本文件的异同处.如果指定要比较目录,则diff会比较目录中相同文件名的文件,但不会比较其中子目录 用 ...

  10. WyBox 7620a 启用第二个串口

    要修改的文件有两个 mt7620a.dtsi MT7620a.dts 1.进入target/linux/ramips/dts/ mt7620a.dtsi 把”disabled”改为”ok”,添加两行 ...