架构师_程序员_码农网

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

搜索
查看: 26662|回复: 2

[资料] Microsoft.Office.Interop.Word操作word模版文档

[复制链接]
发表于 2016-4-8 12:48:10 | 显示全部楼层 |阅读模式
  1. using Microsoft.Office.Interop.Word;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;

  6. namespace TempWord.Function
  7. {
  8.     public class WordHelp
  9.     {
  10.         private _Application wordApp = null;
  11.         private _Document wordDoc = null;
  12.         public _Application Application
  13.         {
  14.             get
  15.             {
  16.                 return wordApp;
  17.             }
  18.             set
  19.             {
  20.                 wordApp = value;
  21.             }
  22.         }
  23.         public _Document Document
  24.         {
  25.             get
  26.             {
  27.                 return wordDoc;
  28.             }
  29.             set
  30.             {
  31.                 wordDoc = value;
  32.             }
  33.         }

  34.         /// <summary>
  35.         /// 通过模板创建新文档
  36.         /// </summary>
  37.         /// <param name="filePath"></param>
  38.         public void CreateNewDocument(string filePath)
  39.         {
  40.             try
  41.             {
  42.                 killWinWordProcess();
  43.                 wordApp = new ApplicationClass();
  44.                 wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
  45.                 wordApp.Visible = false;
  46.                 object missing = System.Reflection.Missing.Value;
  47.                 object templateName = filePath;
  48.                 wordDoc = wordApp.Documents.Open(ref templateName, ref missing,
  49.                     ref missing, ref missing, ref missing, ref missing, ref missing,
  50.                     ref missing, ref missing, ref missing, ref missing, ref missing,
  51.                     ref missing, ref missing, ref missing, ref missing);
  52.             }
  53.             catch (Exception ex)
  54.             {
  55.                 System.Windows.Forms.MessageBox.Show(ex.Message);
  56.             }
  57.         }

  58.         /// <summary>
  59.         /// 保存新文件
  60.         /// </summary>
  61.         /// <param name="filePath"></param>
  62.         public void SaveDocument(string filePath)
  63.         {
  64.             object fileName = filePath;
  65.             object format = WdSaveFormat.wdFormatDocument;//保存格式
  66.             object miss = System.Reflection.Missing.Value;
  67.             wordDoc.SaveAs(ref fileName, ref format, ref miss,
  68.                 ref miss, ref miss, ref miss, ref miss,
  69.                 ref miss, ref miss, ref miss, ref miss,
  70.                 ref miss, ref miss, ref miss, ref miss,
  71.                 ref miss);
  72.             //关闭wordDoc,wordApp对象
  73.             object SaveChanges = WdSaveOptions.wdSaveChanges;
  74.             object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat;
  75.             object RouteDocument = false;
  76.             wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
  77.             wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
  78.         }

  79.         /// <summary>
  80.         /// 在书签处插入值
  81.         /// </summary>
  82.         /// <param name="bookmark"></param>
  83.         /// <param name="value"></param>
  84.         /// <returns></returns>
  85.         public bool InsertValue(string bookmark, string value)
  86.         {
  87.             object bkObj = bookmark;
  88.             if (wordApp.ActiveDocument.Bookmarks.Exists(bookmark))
  89.             {
  90.                 wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
  91.                 wordApp.Selection.TypeText(value);
  92.                 return true;
  93.             }
  94.             return false;
  95.         }

  96.         /// <summary>
  97.         /// 插入表格,bookmark书签
  98.         /// </summary>
  99.         /// <param name="bookmark"></param>
  100.         /// <param name="rows"></param>
  101.         /// <param name="columns"></param>
  102.         /// <param name="width"></param>
  103.         /// <returns></returns>
  104.         public Table InsertTable(string bookmark, int rows, int columns, float width)
  105.         {
  106.             object miss = System.Reflection.Missing.Value;
  107.             object oStart = bookmark;
  108.             Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置
  109.             Table newTable = wordDoc.Tables.Add(range, rows, columns, ref miss, ref miss);
  110.             //设置表的格式
  111.             newTable.Borders.Enable = 1;  //允许有边框,默认没有边框(为0时报错,1为实线边框,2、3为虚线边框,以后的数字没试过)
  112.             newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//边框宽度
  113.             if (width != 0)
  114.             {
  115.                 newTable.PreferredWidth = width;//表格宽度
  116.             }
  117.             newTable.AllowPageBreaks = false;
  118.             return newTable;
  119.         }

  120.         /// <summary>
  121.         /// 合并单元格 表id,开始行号,开始列号,结束行号,结束列号
  122.         /// </summary>
  123.         /// <param name="n"></param>
  124.         /// <param name="row1"></param>
  125.         /// <param name="column1"></param>
  126.         /// <param name="row2"></param>
  127.         /// <param name="column2"></param>
  128.         public void MergeCell(int n, int row1, int column1, int row2, int column2)
  129.         {
  130.             wordDoc.Content.Tables[n].Cell(row1, column1).Merge(wordDoc.Content.Tables[n].Cell(row2, column2));
  131.         }

  132.         /// <summary>
  133.         /// 合并单元格 表名,开始行号,开始列号,结束行号,结束列号
  134.         /// </summary>
  135.         /// <param name="table"></param>
  136.         /// <param name="row1"></param>
  137.         /// <param name="column1"></param>
  138.         /// <param name="row2"></param>
  139.         /// <param name="column2"></param>
  140.         public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2)
  141.         {
  142.             table.Cell(row1, column1).Merge(table.Cell(row2, column2));
  143.         }

  144.         /// <summary>
  145.         /// 设置表格内容对齐方式 Align水平方向,Vertical垂直方向(左对齐,居中对齐,右对齐分别对应Align和Vertical的值为-1,0,1)Microsoft.Office.Interop.Word.Table table
  146.         /// </summary>
  147.         /// <param name="n"></param>
  148.         /// <param name="Align"></param>
  149.         /// <param name="Vertical"></param>
  150.         public void SetParagraph_Table(int n, int Align, int Vertical)
  151.         {
  152.             switch (Align)
  153.             {
  154.                 case -1: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左对齐
  155.                 case 0: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中
  156.                 case 1: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右对齐
  157.             }
  158.             switch (Vertical)
  159.             {
  160.                 case -1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//顶端对齐
  161.                 case 0: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中
  162.                 case 1: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端对齐
  163.             }
  164.         }

  165.         /// <summary>
  166.         /// 设置单元格内容对齐方式
  167.         /// </summary>
  168.         /// <param name="n"></param>
  169.         /// <param name="row"></param>
  170.         /// <param name="column"></param>
  171.         /// <param name="Align"></param>
  172.         /// <param name="Vertical"></param>
  173.         public void SetParagraph_Table(int n, int row, int column, int Align, int Vertical)
  174.         {
  175.             switch (Align)
  176.             {
  177.                 case -1: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左对齐
  178.                 case 0: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中
  179.                 case 1: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右对齐
  180.             }
  181.             switch (Vertical)
  182.             {
  183.                 case -1: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//顶端对齐
  184.                 case 0: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中
  185.                 case 1: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端对齐
  186.             }
  187.             
  188.         }

  189.         /// <summary>
  190.         /// 设置表格字体
  191.         /// </summary>
  192.         /// <param name="table"></param>
  193.         /// <param name="fontName"></param>
  194.         /// <param name="size"></param>
  195.         public void SetFont_Table(Microsoft.Office.Interop.Word.Table table, string fontName, double size)
  196.         {
  197.             if (size != 0)
  198.             {
  199.                 table.Range.Font.Size = Convert.ToSingle(size);
  200.             }
  201.             if (fontName != "")
  202.             {
  203.                 table.Range.Font.Name = fontName;
  204.             }
  205.         }
  206.         
  207.         /// <summary>
  208.         /// 设置单元格字体
  209.         /// </summary>
  210.         /// <param name="n"></param>
  211.         /// <param name="row"></param>
  212.         /// <param name="column"></param>
  213.         /// <param name="fontName"></param>
  214.         /// <param name="size"></param>
  215.         /// <param name="bold"></param>
  216.         public void SetFont_Table(int n, int row, int column, string fontName, double size,int bold)
  217.         {
  218.             if (size != 0)
  219.             {
  220.                 wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Size = Convert.ToSingle(size);
  221.             }
  222.             if (fontName != "")
  223.             {
  224.                 wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Name = fontName;
  225.             }
  226.                 wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Bold = bold;// 0 表示不是粗体,其他值都是
  227.         }
  228.         
  229.         // 是否使用边框,n表格的序号,use是或否
  230.         // 该处边框参数可以用int代替bool可以让方法更全面
  231.         // 具体值方法中介绍
  232.         public void UseBorder(int n,bool use)
  233.         {
  234.             if (use)
  235.             {
  236.                 wordDoc.Content.Tables[n].Borders.Enable = 1;
  237.                 //允许有边框,默认没有边框(为0时无边框,1为实线边框,2、3为虚线边框,以后的数字没试过)
  238.             }
  239.             else
  240.             {
  241.                 wordDoc.Content.Tables[n].Borders.Enable = 0;
  242.             }
  243.         }

  244.         // 给表格插入一行,n表格的序号从1开始记
  245.         public void AddRow(int n)
  246.         {
  247.             object miss = System.Reflection.Missing.Value;
  248.             wordDoc.Content.Tables[n].Rows.Add(ref miss);
  249.         }

  250.         // 给表格添加一行
  251.         public void AddRow(Microsoft.Office.Interop.Word.Table table)
  252.         {
  253.             object miss = System.Reflection.Missing.Value;
  254.             table.Rows.Add(ref miss);
  255.         }

  256.         // 给表格插入rows行,n为表格的序号
  257.         public void AddRow(int n, int rows)
  258.         {
  259.             object miss = System.Reflection.Missing.Value;
  260.             Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
  261.             for (int i = 0; i < rows; i++)
  262.             {
  263.                 table.Rows.Add(ref miss);
  264.             }
  265.         }

  266.         /// <summary>
  267.         /// 删除表格第rows行,n为表格的序号
  268.         /// </summary>
  269.         /// <param name="n"></param>
  270.         /// <param name="row"></param>
  271.         public void DeleteRow(int n, int row)
  272.         {
  273.             Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
  274.             table.Rows[row].Delete();
  275.         }

  276.         /// <summary>
  277.         /// 给表格中单元格插入元素,table所在表格,row行号,column列号,value插入的元素
  278.         /// </summary>
  279.         /// <param name="table"></param>
  280.         /// <param name="row"></param>
  281.         /// <param name="column"></param>
  282.         /// <param name="value"></param>
  283.         public void InsertCell(Microsoft.Office.Interop.Word.Table table, int row, int column, string value)
  284.         {
  285.             table.Cell(row, column).Range.Text = value;
  286.         }

  287.         /// <summary>
  288.         /// 给表格中单元格插入元素,n表格的序号从1开始记,row行号,column列号,value插入的元素
  289.         /// </summary>
  290.         /// <param name="n"></param>
  291.         /// <param name="row"></param>
  292.         /// <param name="column"></param>
  293.         /// <param name="value"></param>
  294.         public void InsertCell(int n, int row, int column, string value)
  295.         {
  296.             wordDoc.Content.Tables[n].Cell(row, column).Range.Text = value;
  297.         }

  298.         /// <summary>
  299.         /// 给表格插入一行数据,n为表格的序号,row行号,columns列数,values插入的值
  300.         /// </summary>
  301.         /// <param name="n"></param>
  302.         /// <param name="row"></param>
  303.         /// <param name="columns"></param>
  304.         /// <param name="values"></param>
  305.         public void InsertCell(int n, int row, int columns, string[] values)
  306.         {
  307.             Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
  308.             for (int i = 0; i < columns; i++)
  309.             {
  310.                 table.Cell(row, i + 1).Range.Text = values[i];
  311.             }
  312.         }

  313.         /// <summary>
  314.         /// 插入图片
  315.         /// </summary>
  316.         /// <param name="bookmark"></param>
  317.         /// <param name="picturePath"></param>
  318.         /// <param name="width"></param>
  319.         /// <param name="hight"></param>
  320.         public void InsertPicture(string bookmark, string picturePath, float width, float hight)
  321.         {
  322.             object miss = System.Reflection.Missing.Value;
  323.             object oStart = bookmark;
  324.             Object linkToFile = false;       //图片是否为外部链接
  325.             Object saveWithDocument = true;  //图片是否随文档一起保存
  326.             object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//图片插入位置
  327.             wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);
  328.             wordDoc.Application.ActiveDocument.InlineShapes[1].Width = width;   //设置图片宽度
  329.             wordDoc.Application.ActiveDocument.InlineShapes[1].Height = hight;  //设置图片高度
  330.        }

  331.         /// <summary>
  332.         /// 插入一段文字,text为文字内容
  333.         /// </summary>
  334.         /// <param name="bookmark"></param>
  335.         /// <param name="text"></param>
  336.         public void InsertText(string bookmark, string text)
  337.         {
  338.             object oStart = bookmark;
  339.             object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;
  340.             Paragraph wp = wordDoc.Content.Paragraphs.Add(ref range);
  341.             wp.Format.SpaceBefore = 6;
  342.             wp.Range.Text = text;
  343.             wp.Format.SpaceAfter = 24;
  344.             wp.Range.InsertParagraphAfter();
  345.             wordDoc.Paragraphs.Last.Range.Text = "\n";
  346.         }

  347.         /// <summary>
  348.         /// 杀掉winword.exe进程
  349.         /// </summary>
  350.         public void killWinWordProcess()
  351.         {
  352.             System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");
  353.             foreach (System.Diagnostics.Process process in processes)
  354.             {
  355.                 bool b = process.MainWindowTitle == "";
  356.                 if (process.MainWindowTitle == "")
  357.                 {
  358.                     process.Kill();
  359.                 }
  360.             }
  361.         }
  362.         public static void killWinWord()
  363.         {
  364.             System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");
  365.             foreach (System.Diagnostics.Process process in processes)
  366.             {
  367.                 bool b = process.MainWindowTitle == "";
  368.                 if (process.MainWindowTitle == "")
  369.                 {
  370.                     process.Kill();
  371.                 }
  372.             }
  373.         }
  374.         //// <summary>
  375.         /// 把Word文件转换成pdf文件
  376.         /// </summary>
  377.         /// <param name="sourcePath">需要转换的文件路径和文件名称</param>
  378.         /// <param name="targetPath">转换完成后的文件的路径和文件名名称</param>
  379.         /// <returns>成功返回true,失败返回false</returns>
  380.         public static bool WordToPdf(object sourcePath, string targetPath)
  381.         {
  382.             bool result = false;
  383.             WdExportFormat wdExportFormatPDF = WdExportFormat.wdExportFormatPDF;
  384.             object missing = Type.Missing;
  385.             Microsoft.Office.Interop.Word.ApplicationClass applicationClass = null;
  386.             Document document = null;
  387.             try
  388.             {
  389.                 applicationClass = new Microsoft.Office.Interop.Word.ApplicationClass();
  390.                 document = applicationClass.Documents.Open(ref sourcePath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
  391.                 if (document != null)
  392.                 {
  393.                     document.ExportAsFixedFormat(targetPath, wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 0, 0, WdExportItem.wdExportDocumentContent, true, true, WdExportCreateBookmarks.wdExportCreateWordBookmarks, true, true, false, ref missing);
  394.                 }
  395.                 result = true;
  396.             }
  397.             catch
  398.             {
  399.                 result = false;
  400.             }
  401.             finally
  402.             {
  403.                 if (document != null)
  404.                 {
  405.                     document.Close(ref missing, ref missing, ref missing);
  406.                     document = null;
  407.                 }
  408.                 if (applicationClass != null)
  409.                 {
  410.                     applicationClass.Quit(ref missing, ref missing, ref missing);
  411.                     applicationClass = null;
  412.                 }
  413.             }
  414.             return result;
  415.         }
  416.     }
  417. }
复制代码






上一篇:无法嵌入互操作类型“Microsoft.Office.Interop.Word.ApplicationClass”。请改用...
下一篇:aspose words破解方法Crack
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
 楼主| 发表于 2016-4-8 12:49:16 | 显示全部楼层
使用方法:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;

  9. namespace TempWord
  10. {
  11.     public partial class Form1 : Form
  12.     {
  13.         private static string TempPath = AppDomain.CurrentDomain.BaseDirectory + "PDF.dot"; //模版

  14.         public Form1()
  15.         {
  16.             InitializeComponent();
  17.         }

  18.         private void button1_Click(object sender, EventArgs e)
  19.         {
  20.             try
  21.             {
  22.                 string doc = AppDomain.CurrentDomain.BaseDirectory + "temp.doc";    //生成后的doc
  23.                 string pdf=AppDomain.CurrentDomain.BaseDirectory + "temp.pdf";      //生成后的pdf
  24.                 System.IO.File.Delete(doc);
  25.                 Function.WordHelp word = new Function.WordHelp();
  26.                 word.CreateNewDocument(TempPath);
  27.                 word.InsertValue("项目", "P2P跑路计划");
  28.                 word.InsertValue("招商负责人", "张山");
  29.                 word.InsertValue("日期", DateTime.Now.ToString());
  30.                 word.InsertValue("版本", "v1.0");
  31.                 word.SaveDocument(doc);
  32.                 MessageBox.Show("生成成功,现在正在尝试导出PDF");
  33.                 Function.WordHelp.WordToPdf(doc, pdf);
  34.                 MessageBox.Show("success");

  35.             }
  36.             catch (Exception ex)
  37.             {
  38.                 Function.WordHelp.killWinWord();
  39.             }
  40.         }
  41.     }
  42. }
复制代码


码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
 楼主| 发表于 2016-4-8 15:19:04 | 显示全部楼层
在书签插入图片   会有点问题

  1. /// <summary>
  2.         /// 插入图片
  3.         /// </summary>
  4.         /// <param name="bookmark"></param>
  5.         /// <param name="picturePath"></param>
  6.         /// <param name="width"></param>
  7.         /// <param name="hight"></param>
  8.         public void InsertPicture(string bookmark, string picturePath, float width, float hight)
  9.         {
  10.             object miss = System.Reflection.Missing.Value;
  11.             object oStart = bookmark;
  12.             Object linkToFile = false;       //图片是否为外部链接
  13.             Object saveWithDocument = true;  //图片是否随文档一起保存
  14.             object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//图片插入位置
  15.             InlineShape inlineShape=wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);
  16.             //wordDoc.Application.ActiveDocument.InlineShapes[1].Width = width;   //设置图片宽度
  17.             //wordDoc.Application.ActiveDocument.InlineShapes[1].Height = hight;  //设置图片高度
  18.             inlineShape.Width = width;   //设置图片宽度
  19.             inlineShape.Height = hight;  //设置图片高度
  20.         }
复制代码


码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

免责声明:
码农网所发布的一切软件、编程资料或者文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。

Mail To:help@itsvse.com

QQ|小黑屋|架构师 ( 鲁ICP备14021824号-2 )|网站地图

GMT+8, 2026-4-12 21:33

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表