转:http://www.cnblogs.com/lantionzy/archive/2009/10/23/1588511.html

  1、新建Word文档


#region 新建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;
    }
}
#endregion 新建Word文档

  2、给word文档添加页眉页脚


#region 给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;
    }
}
#endregion 给word文档添加页眉页脚

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


#region 设置文档格式并添加文本内容、超链接
/// <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;
    }
}
#endregion 设置文档格式并添加文本内容、超链接

  4、添加图片


#region 文档中添加图片
/// <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;
    }
}
#endregion 文档中添加图片

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


#region 表格处理(插入表格、设置格式、填充内容)
/// <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, 12, 3, ref oMissing, ref oMissing);
        //设置表格
        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).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 = "座右铭:";
        //设置单元格内字体颜色
        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 = "雷鑫";
        //纵向合并单元格
        newTable.Cell(3, 3).Select();
        //选中一行
        object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
        object moveCount = 3;
        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[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 = "备注:";
        newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
        //在表格中增加行
        WordDoc.Content.Tables[1].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;
    }
}
#endregion #region 表格处理

  6、把Word文档转化为Html文件


#region 把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 });
        #region 其它格式:
        ///wdFormatHTML
        ///wdFormatDocument
        ///wdFormatDOSText
        ///wdFormatDOSTextLineBreaks
        ///wdFormatEncodedText
        ///wdFormatRTF
        ///wdFormatTemplate
        ///wdFormatText
        ///wdFormatTextLineBreaks
        ///wdFormatUnicodeText
        // 退出 Word
        //wordType.InvokeMember( "Quit", System.Reflection.BindingFlags.InvokeMethod,
        //    null, WordApp, null );
        #endregion

        //保存
        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;
    }
}
#endregion 把Word文档转化为Html文件

可以从这里下载整个类(包含更多内容)

WordOperate cs file

C#word(2007)操作类--新建文档、添加页眉页脚、设置格式、添加文本和超链接、添加图片、表格处理、文档格式转化的更多相关文章

  1. C# 操作Word页眉页脚——奇偶页/首页不同、不连续设置页码、复制页眉页脚、锁定页眉页脚、删除页眉页脚

    前言 本文是对Word页眉页脚的操作方法的进一步的阐述.在“C# 添加Word页眉页脚.页码”一文中,介绍了添加简单页眉页脚的方法,该文中的方法可满足于大多数的页眉页脚添加要求,但是对于比较复杂一点的 ...

  2. 【itext】7步制作兼容各种文档格式的Itext5页眉页脚 实现page x pf y

    itext5页眉页脚工具类,实现page x of y 完美兼容各种格式大小文档A4/B5/B3,兼容各种文档格式自动计算页脚XY轴坐标 鉴于没人做的这么细致,自己就写了一个itext5页眉页脚工具类 ...

  3. ABBYY FineReader 15 如何为PDF文档添加页眉页脚

    页眉.页脚是文档页面顶部或底部重复出现的文本信息.很多用户会习惯在文档页面的顶部与底部区域添加页眉.页脚来展现页码.文档标题.作者姓名.品牌名称等附加信息.而ABBYY FineReader 15(W ...

  4. 在C#中实现Word页眉页脚的全部功能

    页眉页脚经常使用于文章排版,在Word工具栏里.我们能够加入页眉,页脚,页码,日期和时间.图片等信息和内容.页眉/页脚有两个额外选项:首页不同,奇偶页不同.有时在不同的节(section)里插入不同的 ...

  5. Office WORD如何为每一页设置不同的页眉页脚

    如下图所示,我想要为封面和目录,摘要等等设置不同的页眉页脚(一般封面和目录不需要页脚)   而从正文开始,套用相同的页眉和以页数作为页脚(注意"第一章 绪论"不是这个文档的第一页) ...

  6. 使用C#在word中插入页眉页脚

    //插入页脚 public void InsertFooter(string footer) { if (ActiveWindow.ActivePane.View.Type == WdViewType ...

  7. Word中页眉、页码设置

    本篇博文简单介绍一下文档中页眉.页码设置的问题 一个项目中,封面一般不需要页眉,要关闭首页的页眉,可以在"页眉和页脚工具->选项->首页不同"可以如下设置: 图 1关闭 ...

  8. 有哪位大侠操作过NPOI生成word文档,如何设置页眉页脚距离顶部和底部距离?

    #region 1.创建文档(页眉.页脚) XWPFDocument doc = new XWPFDocument(); //页面设置 A4:w=11906 h=16838 doc.Document. ...

  9. C#操作word的一些基本方法(word打印,插入文件,插入图片,定位页眉页脚,去掉横线)

    Microsoft.Office.Interop.Word.Application wordApp = new ApplicationClass() word对象 2. Microsoft.Offic ...

随机推荐

  1. 关于win8.1“连接被远程计算机关闭”的一种解决方案

    我就是连接的时候出现"连接被远程计算机关闭",然后想着可能是win8更新之后网络协议 出问题了,后来无意中发现e信在第一次启动的时候会在网络适配器中会多出很多网卡,其中三个是带感叹 ...

  2. Phalcon的学习篇-phalcon和devtools的安装和设置

    A Phalcon在Windows上的安装 1 从Phalcon for Windows下载适合的DLL, 这里的适合 主要看两个方面 1 PHP的版本 2 线程是否是安全 3 编译版本 如果不清楚这 ...

  3. [POJ 1742] Coins 【DP】

    题目链接:POJ - 1742 题目大意 现有 n 种不同的硬币,每种的面值为 Vi ,数量为 Ni ,问使用这些硬币共能凑出 [1,m] 范围内的多少种面值. 题目分析 使用一种 O(nm) 的 D ...

  4. 【Java】Java 序列化的高级认识

    如果你只知道实现 Serializable 接口的对象,可以序列化为本地文件.那你最好再阅读该篇文章,文章对序列化进行了更深一步的讨论,用实际的例子代码讲述了序列化的高级认识,包括父类序列化的问题.静 ...

  5. CentOS 5升级Python版本(2.4>2.7)

    安装SALT时,需要这样作,公司有一批REDHAT5的,弄起来... 然后却是: Missing Dependency: python(abi) = 2.6 is needed by package ...

  6. MSP430的IO口模拟I2C总线对AT24C25进行读写程序

    功能: 实现MSP430口线模拟I2C总线协议与24C04通信.                                           ** 描述: 主系统工作时钟为12MHz,I2C工 ...

  7. Qt入门(10)——调试技术

    命令行参数当你运行Qt程序时,你可以指定几个命令行参数来帮助你调试.-nograb 应用程序不再捕获鼠标或者键盘.当程序在Linux下运行在gdb调试器中时这个选项是默认的.-dograb 忽略任何隐 ...

  8. 阿里云ECS试用

    公司在推一个大项目,感觉阿里云挺好用的,自己搞了台小机器平时可以跑着玩,而且可以做个跳板机,平时学校里的收费网直接用跳板机就可以访问了,直接写个脚本在自己机器上跑一下: #!/usr/bin/expe ...

  9. 开源库CImg 数据格式存储之二(RGB 顺序)

    在上一篇博客中已经初步说明了GDI和CImg数据的存储格式感谢博友 Imageshop 评论说明 CImg的说明文档中已有详细说明(详见上篇博客说明) CImg的数据格式确实是RRRGGGBBB顺序存 ...

  10. log4cxx在vs2013的静态编译

    网络上找了一圈,结果都是通过修改代码来编译,做为强迫症患者接受不了这种修改代码却无法预知代码带来影响的方式,而且没有静态编译的方法,为了方便其他人后续不在走弯路,提供自己的编译方法. 虽然最终的目的是 ...