分类目录

链接

2015 年 12 月
 123456
78910111213
14151617181920
21222324252627
28293031  

近期文章

热门标签

新人福利,免费薅羊毛

现在位置:    首页 > .NET > 正文
C#操作Word类库
.NET 评论(1) 阅读(1,889)
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using Microsoft.Office.Interop.Word;
  5. using System.IO;
  6. using System.Web;
  7. using System.Data;
  8. using System.Reflection;
  9. using Microsoft.Win32;
  10. using System.Text.RegularExpressions;
  11. using System.Net;
  12. namespace OfficeOperate
  13. {
  14.     public class WordOperate
  15.     {
  16.         #region 动态生成Word文档并填充数据
  17.         /**//// <summary>
  18.         /// 动态生成Word文档并填充数据
  19.         /// </summary>
  20.         /// <returns>返回自定义信息</returns>
  21.         public static string CreateWordFile()
  22.         {
  23.             string message = "";
  24.             try
  25.             {
  26.                 Object oMissing = System.Reflection.Missing.Value;
  27.                 string dir = System.Web.HttpContext.Current.Server.MapPath( "" );//首先在类库添加using System.web的引用
  28.                 if( !Directory.Exists( dir + "//file" ) )
  29.                 {
  30.                     Directory.CreateDirectory( dir + "//file" );  //创建文件所在目录
  31.                 }
  32.                 string name = DateTime.Now.ToLongDateString() + ".doc";
  33.                 object filename = dir + "//file//" + name;  //文件保存路径
  34.                 //创建Word文档
  35.                 Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
  36.                 Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
  37.                 /**/////添加页眉方法一:
  38.                 //WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
  39.                 //WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
  40.                 //WordApp.ActiveWindow.ActivePane.Selection.InsertAfter( "无锡全真通科技有限公司" );//页眉内容
  41.                 //添加页眉方法二:
  42.                 if( WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdNormalView || WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdOutlineView )
  43.                 {
  44.                     WordApp.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView;
  45.                 }
  46.                 WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;
  47.                 string sHeader = "页眉内容";
  48.                 WordApp.Selection.HeaderFooter.LinkToPrevious = false;
  49.                 WordApp.Selection.HeaderFooter.Range.Text = sHeader;
  50.                 WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
  51.                 //WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐
  52.                 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;//设置左对齐  
  53.                 WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置
  54.                 WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距
  55.                 //移动焦点并换行
  56.                 object count = 14;
  57.                 object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行;
  58.                 WordApp.Selection.MoveDown( ref WdLine, ref count, ref oMissing );//移动焦点
  59.                 WordApp.Selection.TypeParagraph();//插入段落
  60.                 //文档中创建表格
  61.                 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add( WordApp.Selection.Range, 12, 3, ref oMissing, ref oMissing );
  62.                 //设置表格样式
  63.                 newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
  64.                 newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
  65.                 newTable.Columns[1].Width = 100f;
  66.                 newTable.Columns[2].Width = 220f;
  67.                 newTable.Columns[3].Width = 105f;
  68.                 //填充表格内容
  69.                 newTable.Cell( 1, 1 ).Range.Text = "产品详细信息表";
  70.                 newTable.Cell( 1, 1 ).Range.Bold = 2;//设置单元格中字体为粗体
  71.                 //合并单元格
  72.                 newTable.Cell( 1, 1 ).Merge( newTable.Cell( 1, 3 ) );
  73.                 WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
  74.                 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
  75.                 //填充表格内容
  76.                 newTable.Cell( 2, 1 ).Range.Text = "产品基本信息";
  77.                 newTable.Cell( 2, 1 ).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
  78.                 //合并单元格
  79.                 newTable.Cell( 2, 1 ).Merge( newTable.Cell( 2, 3 ) );
  80.                 WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
  81.                 //填充表格内容
  82.                 newTable.Cell( 3, 1 ).Range.Text = "品牌名称:";
  83.                 newTable.Cell( 3, 2 ).Range.Text = "BrandName";
  84.                 //纵向合并单元格
  85.                 newTable.Cell( 3, 3 ).Select();//选中一行
  86.                 object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
  87.                 object moveCount = 5;
  88.                 object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
  89.                 WordApp.Selection.MoveDown( ref moveUnit, ref moveCount, ref moveExtend );
  90.                 WordApp.Selection.Cells.Merge();
  91.                 //插入图片
  92.                 if( File.Exists( System.Web.HttpContext.Current.Server.MapPath( "images//picture.jpg" ) ) )
  93.                 {
  94.                     string FileName = System.Web.HttpContext.Current.Server.MapPath( "images//picture.jpg" );//图片所在路径
  95.                     object LinkToFile = false;
  96.                     object SaveWithDocument = true;
  97.                     object Anchor = WordDoc.Application.Selection.Range;
  98.                     WordDoc.Application.ActiveDocument.InlineShapes.AddPicture( FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor );
  99.                     WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度
  100.                     WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度
  101.                 }
  102.                 //将图片设置为四周环绕型
  103.                 Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
  104.                 s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;
  105.                 newTable.Cell( 12, 1 ).Range.Text = "产品特殊属性";
  106.                 newTable.Cell( 12, 1 ).Merge( newTable.Cell( 12, 3 ) );
  107.                 //在表格中增加行
  108.                 WordDoc.Content.Tables[1].Rows.Add( ref oMissing );
  109.                 WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();//“落款”
  110.                 WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
  111.                 //文件保存
  112.                 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 );
  113.                 WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );
  114.                 WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );
  115.                 message = name + "文档生成成功";
  116.             }
  117.             catch
  118.             {
  119.                 message = "文件导出异常!";
  120.             }
  121.             return message;
  122.         }
  123.         #endregion       
  124.         #region 创建并打开一个空的word文档进行编辑
  125.         /**//// <summary>
  126.         /// 创建并打开一个空的word文档进行编辑
  127.         /// </summary>
  128.         public static void OpenNewWordFileToEdit()
  129.         {
  130.             object oMissing = System.Reflection.Missing.Value;
  131.             Microsoft.Office.Interop.Word.Application WordApp;
  132.             Microsoft.Office.Interop.Word.Document WordDoc;
  133.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
  134.             WordApp.Visible = true;
  135.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
  136.         }
  137.         #endregion
  138.         #region 创建word文档
  139.         /**//// <summary>
  140.         /// 创建word文档
  141.         /// </summary>
  142.         /// <returns></returns>
  143.         public static string createWord()
  144.         {
  145.             Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
  146.             Document WordDoc;
  147.             string strContent = "";
  148.             object strFileName = System.Web.HttpContext.Current.Server.MapPath( "test.doc " );
  149.             if( System.IO.File.Exists( (string)strFileName ) )
  150.                 System.IO.File.Delete( (string)strFileName );
  151.             Object oMissing = System.Reflection.Missing.Value;
  152.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
  153.             #region   将数据库中读取得数据写入到word文件中
  154.             strContent = "你好/n/n/r ";
  155.             WordDoc.Paragraphs.Last.Range.Text = strContent;
  156.             strContent = "这是测试程序 ";
  157.             WordDoc.Paragraphs.Last.Range.Text = strContent;
  158.             #endregion
  159.             //将WordDoc文档对象的内容保存为DOC文档  
  160.             WordDoc.SaveAs( ref strFileName, 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 );
  161.             //关闭WordDoc文档对象  
  162.             WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );
  163.             //关闭WordApp组件对象  
  164.             WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );
  165.             string message = strFileName + "/r/n " + "创建成功 ";
  166.             return message;
  167.         }
  168.         #endregion
  169.         #region Word文档装化为Html文件
  170.         /**//// <summary>
  171.         /// 把Word文档装化为Html文件
  172.         /// </summary>
  173.         /// <param name="strFileName">要转换的Word文档</param>
  174.         public static void WordToHtml( string strFileName )
  175.         {
  176.             string saveFileName = strFileName + DateTime.Now.ToString( "yyyy-MM-dd-HH-mm-ss" ) + ".html";
  177.             WordToHtml( strFileName, saveFileName );
  178.         }
  179.         /**//// <summary>
  180.         /// 把Word文档装化为Html文件
  181.         /// </summary>
  182.         /// <param name="strFileName">要转换的Word文档</param>
  183.         /// <param name="strSaveFileName">要生成的具体的Html页面</param>
  184.         public static void WordToHtml( string strFileName, string strSaveFileName )
  185.         {
  186.             Microsoft.Office.Interop.Word.ApplicationClass WordApp;
  187.             Microsoft.Office.Interop.Word.Document WordDoc;
  188.             Object oMissing = System.Reflection.Missing.Value;
  189.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
  190.             object fileName = strFileName;
  191.  
  192.             WordDoc = WordApp.Documents.Open( ref fileName,
  193.                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
  194.                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
  195.                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing );
  196.             Type wordType = WordApp.GetType();
  197.             // 打开文件
  198.             Type docsType = WordApp.Documents.GetType();
  199.             // 转换格式,另存为
  200.             Type docType = WordDoc.GetType();
  201.             object saveFileName = strSaveFileName;
  202.             docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, WordDoc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML } );
  203.             #region 其它格式:
  204.             /**//**/
  205.             /**////wdFormatHTML
  206.             ///wdFormatDocument
  207.             ///wdFormatDOSText
  208.             ///wdFormatDOSTextLineBreaks
  209.             ///wdFormatEncodedText
  210.             ///wdFormatRTF
  211.             ///wdFormatTemplate
  212.             ///wdFormatText
  213.             ///wdFormatTextLineBreaks
  214.             ///wdFormatUnicodeText
  215.             //--------------------------------------------------------------------------            //            docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod,
  216.             //                null, WordDoc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML} );
  217.             // 退出 Word
  218.             //wordType.InvokeMember( "Quit", System.Reflection.BindingFlags.InvokeMethod,
  219.             //    null, WordApp, null );
  220.             #endregion
  221.             WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );
  222.             WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );
  223.         }
  224.         #endregion
  225.         #region 导入模板
  226.         /**//// <summary>
  227.         /// 导入模板
  228.         /// </summary>
  229.         /// <param name="filePath">模板文档路径</param>
  230.         public static void ImportTemplate( string filePath )
  231.         {
  232.             object oMissing = System.Reflection.Missing.Value;
  233.             Microsoft.Office.Interop.Word.Application WordApp;
  234.             Microsoft.Office.Interop.Word.Document WordDoc;
  235.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
  236.             WordApp.Visible = true;
  237.             object fileName = filePath;
  238.             WordDoc = WordApp.Documents.Add( ref fileName, ref oMissing, ref oMissing, ref oMissing );
  239.         }
  240.         #endregion
  241.         #region word中添加新表
  242.         /**//// <summary>
  243.         /// word中添加新表
  244.         /// </summary>
  245.         public static void AddTable()
  246.         {
  247.             object oMissing = System.Reflection.Missing.Value;
  248.             Microsoft.Office.Interop.Word.Application WordApp;
  249.             Microsoft.Office.Interop.Word.Document WordDoc;
  250.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
  251.             WordApp.Visible = true;
  252.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
  253.             object start = 0;
  254.             object end = 0;
  255.             Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
  256.             WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );//3行4列的表
  257.         }
  258.         #endregion
  259.         #region 在表中插入新行
  260.         /**//// <summary>
  261.         /// 在表中插入新的1行
  262.         /// </summary>
  263.         public static void AddRow()
  264.         {
  265.             object oMissing = System.Reflection.Missing.Value;
  266.             Microsoft.Office.Interop.Word.Application WordApp;
  267.             Microsoft.Office.Interop.Word.Document WordDoc;
  268.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
  269.             WordApp.Visible = true;
  270.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
  271.             object start = 0;
  272.             object end = 0;
  273.             Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
  274.             WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );
  275.             Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
  276.             object beforeRow = newTable.Rows[1];
  277.             newTable.Rows.Add( ref beforeRow );
  278.         }
  279.         #endregion
  280.         #region 分离单元格
  281.         /**//// <summary>
  282.         /// 合并单元格
  283.         /// </summary>
  284.         public static void CombinationCell()
  285.         {
  286.             object oMissing = System.Reflection.Missing.Value;
  287.             Microsoft.Office.Interop.Word.Application WordApp;
  288.             Microsoft.Office.Interop.Word.Document WordDoc;
  289.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
  290.             WordApp.Visible = true;
  291.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
  292.             object start = 0;
  293.             object end = 0;
  294.             Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
  295.             WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );
  296.             Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
  297.             object beforeRow = newTable.Rows[1];
  298.             newTable.Rows.Add( ref beforeRow );
  299.             Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 2, 1 );//2行1列合并2行2列为一起
  300.             cell.Merge( newTable.Cell( 2, 2 ) );
  301.             //cell.Merge( newTable.Cell( 1, 3 ) );
  302.         }
  303.         #endregion
  304.         #region 分离单元格
  305.         /**//// <summary>
  306.         /// 分离单元格
  307.         /// </summary>
  308.         public static void SeparateCell()
  309.         {
  310.             object oMissing = System.Reflection.Missing.Value;
  311.             Microsoft.Office.Interop.Word.Application WordApp;
  312.             Microsoft.Office.Interop.Word.Document WordDoc;
  313.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
  314.             WordApp.Visible = true;
  315.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
  316.             object start = 0;
  317.             object end = 0;
  318.             Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
  319.             WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );
  320.             Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
  321.             object beforeRow = newTable.Rows[1];
  322.             newTable.Rows.Add( ref beforeRow );
  323.             Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 1, 1 );
  324.             cell.Merge( newTable.Cell( 1, 2 ) );
  325.             object Rownum = 2;
  326.             object Columnnum = 2;
  327.             cell.Split( ref Rownum, ref  Columnnum );
  328.         }
  329.         #endregion
  330.         #region 通过段落控制插入Insert a paragraph at the beginning of the document.
  331.         /**//// <summary>
  332.         /// 通过段落控制插入Insert a paragraph at the beginning of the document.
  333.         /// </summary>
  334.         public static void Insert()
  335.         {
  336.             object oMissing = System.Reflection.Missing.Value;
  337.             //object oEndOfDoc = "//endofdoc"; /**//* /endofdoc is a predefined bookmark */
  338.             //Start Word and create a new document.
  339.             Microsoft.Office.Interop.Word.Application WordApp;
  340.             Microsoft.Office.Interop.Word.Document WordDoc;
  341.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
  342.             WordApp.Visible = true;
  343.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
  344.             //Insert a paragraph at the beginning of the document.
  345.             Microsoft.Office.Interop.Word.Paragraph oPara1;
  346.             oPara1 = WordDoc.Content.Paragraphs.Add( ref oMissing );
  347.             oPara1.Range.Text = "Heading 1";
  348.             oPara1.Range.Font.Bold = 1;
  349.             oPara1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.
  350.             oPara1.Range.InsertParagraphAfter();
  351.         }
  352.         #endregion
  353.         #region word文档设置及获取光标位置
  354.         /**//// <summary>
  355.         /// word文档设置及获取光标位置
  356.         /// </summary>
  357.         public static void WordSet()
  358.         {
  359.             object oMissing = System.Reflection.Missing.Value;
  360.             Microsoft.Office.Interop.Word.Application WordApp;
  361.             Microsoft.Office.Interop.Word.Document WordDoc;
  362.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
  363.             #region 文档格式设置
  364.             WordApp.ActiveDocument.PageSetup.LineNumbering.Active = 0;//行编号
  365.             WordApp.ActiveDocument.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;//页面方向
  366.             WordApp.ActiveDocument.PageSetup.TopMargin = WordApp.CentimetersToPoints( float.Parse( "2.54" ) );//上页边距
  367.             WordApp.ActiveDocument.PageSetup.BottomMargin = WordApp.CentimetersToPoints( float.Parse( "2.54" ) );//下页边距
  368.             WordApp.ActiveDocument.PageSetup.LeftMargin = WordApp.CentimetersToPoints( float.Parse( "3.17" ) );//左页边距
  369.             WordApp.ActiveDocument.PageSetup.RightMargin = WordApp.CentimetersToPoints( float.Parse( "3.17" ) );//右页边距
  370.             WordApp.ActiveDocument.PageSetup.Gutter = WordApp.CentimetersToPoints( float.Parse( "0" ) );//装订线位置
  371.             WordApp.ActiveDocument.PageSetup.HeaderDistance = WordApp.CentimetersToPoints( float.Parse( "1.5" ) );//页眉
  372.             WordApp.ActiveDocument.PageSetup.FooterDistance = WordApp.CentimetersToPoints( float.Parse( "1.75" ) );//页脚
  373.             WordApp.ActiveDocument.PageSetup.PageWidth = WordApp.CentimetersToPoints( float.Parse( "21" ) );//纸张宽度
  374.             WordApp.ActiveDocument.PageSetup.PageHeight = WordApp.CentimetersToPoints( float.Parse( "29.7" ) );//纸张高度
  375.             WordApp.ActiveDocument.PageSetup.FirstPageTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源
  376.             WordApp.ActiveDocument.PageSetup.OtherPagesTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源
  377.             WordApp.ActiveDocument.PageSetup.SectionStart = Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage;//节的起始位置:新建页
  378.             WordApp.ActiveDocument.PageSetup.OddAndEvenPagesHeaderFooter = 0;//页眉页脚-奇偶页不同
  379.             WordApp.ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = 0;//页眉页脚-首页不同
  380.             WordApp.ActiveDocument.PageSetup.VerticalAlignment = Microsoft.Office.Interop.Word.WdVerticalAlignment.wdAlignVerticalTop;//页面垂直对齐方式
  381.             WordApp.ActiveDocument.PageSetup.SuppressEndnotes = 0;//不隐藏尾注
  382.             WordApp.ActiveDocument.PageSetup.MirrorMargins = 0;//不设置首页的内外边距
  383.             WordApp.ActiveDocument.PageSetup.TwoPagesOnOne = false;//不双面打印
  384.             WordApp.ActiveDocument.PageSetup.BookFoldPrinting = false;//不设置手动双面正面打印
  385.             WordApp.ActiveDocument.PageSetup.BookFoldRevPrinting = false;//不设置手动双面背面打印
  386.             WordApp.ActiveDocument.PageSetup.BookFoldPrintingSheets = 1;//打印默认份数
  387.             WordApp.ActiveDocument.PageSetup.GutterPos = Microsoft.Office.Interop.Word.WdGutterStyle.wdGutterPosLeft;//装订线位于左侧
  388.             WordApp.ActiveDocument.PageSetup.LinesPage = 40;//默认页行数量
  389.             WordApp.ActiveDocument.PageSetup.LayoutMode = Microsoft.Office.Interop.Word.WdLayoutMode.wdLayoutModeLineGrid;//版式模式为“只指定行网格”
  390.             #endregion
  391.             #region 段落格式设定
  392.             WordApp.Selection.ParagraphFormat.LeftIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//左缩进
  393.             WordApp.Selection.ParagraphFormat.RightIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//右缩进
  394.             WordApp.Selection.ParagraphFormat.SpaceBefore = float.Parse( "0" );//段前间距
  395.             WordApp.Selection.ParagraphFormat.SpaceBeforeAuto = 0;//
  396.             WordApp.Selection.ParagraphFormat.SpaceAfter = float.Parse( "0" );//段后间距
  397.             WordApp.Selection.ParagraphFormat.SpaceAfterAuto = 0;//
  398.             WordApp.Selection.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;//单倍行距
  399.             WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;//段落2端对齐
  400.             WordApp.Selection.ParagraphFormat.WidowControl = 0;//孤行控制
  401.             WordApp.Selection.ParagraphFormat.KeepWithNext = 0;//与下段同页
  402.             WordApp.Selection.ParagraphFormat.KeepTogether = 0;//段中不分页
  403.             WordApp.Selection.ParagraphFormat.PageBreakBefore = 0;//段前分页
  404.             WordApp.Selection.ParagraphFormat.NoLineNumber = 0;//取消行号
  405.             WordApp.Selection.ParagraphFormat.Hyphenation = 1;//取消段字
  406.             WordApp.Selection.ParagraphFormat.FirstLineIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//首行缩进
  407.             WordApp.Selection.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevelBodyText;
  408.             WordApp.Selection.ParagraphFormat.CharacterUnitLeftIndent = float.Parse( "0" );
  409.             WordApp.Selection.ParagraphFormat.CharacterUnitRightIndent = float.Parse( "0" );
  410.             WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = float.Parse( "0" );
  411.             WordApp.Selection.ParagraphFormat.LineUnitBefore = float.Parse( "0" );
  412.             WordApp.Selection.ParagraphFormat.LineUnitAfter = float.Parse( "0" );
  413.             WordApp.Selection.ParagraphFormat.AutoAdjustRightIndent = 1;
  414.             WordApp.Selection.ParagraphFormat.DisableLineHeightGrid = 0;
  415.             WordApp.Selection.ParagraphFormat.FarEastLineBreakControl = 1;
  416.             WordApp.Selection.ParagraphFormat.WordWrap = 1;
  417.             WordApp.Selection.ParagraphFormat.HangingPunctuation = 1;
  418.             WordApp.Selection.ParagraphFormat.HalfWidthPunctuationOnTopOfLine = 0;
  419.             WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndAlpha = 1;
  420.             WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 1;
  421.             WordApp.Selection.ParagraphFormat.BaseLineAlignment = Microsoft.Office.Interop.Word.WdBaselineAlignment.wdBaselineAlignAuto;
  422.             #endregion
  423.             #region 字体格式设定
  424.             WordApp.Selection.Font.NameFarEast = "华文中宋";
  425.             WordApp.Selection.Font.NameAscii = "Times New Roman";
  426.             WordApp.Selection.Font.NameOther = "Times New Roman";
  427.             WordApp.Selection.Font.Name = "宋体";
  428.             WordApp.Selection.Font.Size = float.Parse( "14" );
  429.             WordApp.Selection.Font.Bold = 0;
  430.             WordApp.Selection.Font.Italic = 0;
  431.             WordApp.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;
  432.             WordApp.Selection.Font.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
  433.             WordApp.Selection.Font.StrikeThrough = 0;//删除线
  434.             WordApp.Selection.Font.DoubleStrikeThrough = 0;//双删除线
  435.             WordApp.Selection.Font.Outline = 0;//空心
  436.             WordApp.Selection.Font.Emboss = 0;//阳文
  437.             WordApp.Selection.Font.Shadow = 0;//阴影
  438.             WordApp.Selection.Font.Hidden = 0;//隐藏文字
  439.             WordApp.Selection.Font.SmallCaps = 0;//小型大写字母
  440.             WordApp.Selection.Font.AllCaps = 0;//全部大写字母
  441.             WordApp.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
  442.             WordApp.Selection.Font.Engrave = 0;//阴文
  443.             WordApp.Selection.Font.Superscript = 0;//上标
  444.             WordApp.Selection.Font.Subscript = 0;//下标
  445.             WordApp.Selection.Font.Spacing = float.Parse( "0" );//字符间距
  446.             WordApp.Selection.Font.Scaling = 100;//字符缩放
  447.             WordApp.Selection.Font.Position = 0;//位置
  448.             WordApp.Selection.Font.Kerning = float.Parse( "1" );//字体间距调整
  449.             WordApp.Selection.Font.Animation = Microsoft.Office.Interop.Word.WdAnimation.wdAnimationNone;//文字效果
  450.             WordApp.Selection.Font.DisableCharacterSpaceGrid = false;
  451.             WordApp.Selection.Font.EmphasisMark = Microsoft.Office.Interop.Word.WdEmphasisMark.wdEmphasisMarkNone;
  452.             #endregion
  453.             #region 获取光标位置
  454.             /**/////get_Information
  455.             WordApp.Selection.get_Information( WdInformation.wdActiveEndPageNumber );
  456.             //关于行号-页号-列号-位置
  457.             //information 属性
  458.             //返回有关指定的所选内容或区域的信息。variant 类型,只读。
  459.             //expression.information(type)
  460.             //expression 必需。该表达式返回一个 range 或 selection 对象。
  461.             //type long 类型,必需。需要返回的信息。可取下列 wdinformation 常量之一:
  462.             //wdactiveendadjustedpagenumber 返回页码,在该页中包含指定的所选内容或区域的活动结尾。如果设置了一个起始页码,并对页码进行了手工调整,则返回调整过的页码。
  463.             //wdactiveendpagenumber 返回页码,在该页中包含指定的所选内容或区域的活动结尾,页码从文档的开头开始计算而不考虑对页码的任何手工调整。
  464.             //wdactiveendsectionnumber 返回节号,在该节中包含了指定的所选内容或区域的活动结尾。
  465.             //wdatendofrowmarker 如果指定的所选内容或区域位于表格的行结尾标记处,则本参数返回 true。
  466.             //wdcapslock 如果大写字母锁定模式有效,则本参数返回 true。
  467.             //wdendofrangecolumnnumber 返回表格列号,在该表格列中包含了指定的所选内容或区域的活动结尾。
  468.             //wdendofrangerownumber 返回表格行号,在该表格行包含了指定的所选内容或区域的活动结尾。
  469.             //wdfirstcharactercolumnnumber 返回指定的所选内容或区域中第一个字符的位置。如果所选内容或区域是折叠的,则返回所选内容或区域右侧紧接着的字符编号。
  470.             //wdfirstcharacterlinenumber 返回所选内容中第一个字符的行号。如果 pagination 属性为 false,或 draft 属性为 true,则返回 - 1。
  471.             //wdframeisselected 如果所选内容或区域是一个完整的图文框文本框,则本参数返回 true。
  472.             //wdheaderfootertype 返回一个值,该值表明包含了指定的所选内容或区域的页眉或页脚的类型,如下表所示。 值 页眉或页脚的类型
  473.             //- 1 无
  474.             //0 偶数页页眉
  475.             //1 奇数页页眉
  476.             //2 偶数页页脚
  477.             //3 奇数页页脚
  478.             //4 第一个页眉
  479.             //5 第一个页脚
  480.             //wdhorizontalpositionrelativetopage 返回指定的所选内容或区域的水平位置。该位置是所选内容或区域的左边与页面的左边之间的距离,以磅为单位。如果所选内容或区域不可见,则返回 - 1。
  481.             //wdhorizontalpositionrelativetotextboundary 返回指定的所选内容或区域相对于周围最近的正文边界的左边的水平位置,以磅为单位。如果所选内容或区域没有显示在当前屏幕,则本参数返回 - 1。
  482.             //wdinclipboard 有关此常量的详细内容,请参阅 microsoft office 98 macintosh 版的语言参考帮助。
  483.             //wdincommentpane 如果指定的所选内容或区域位于批注窗格,则返回 true。
  484.             //wdinendnote 如果指定的所选内容或区域位于页面视图的尾注区内,或者位于普通视图的尾注窗格中,则本参数返回 true。
  485.             //wdinfootnote 如果指定的所选内容或区域位于页面视图的脚注区内,或者位于普通视图的脚注窗格中,则本参数返回 true。
  486.             //wdinfootnoteendnotepane 如果指定的所选内容或区域位于页面视图的脚注或尾注区内,或者位于普通视图的脚注或尾注窗格中,则本参数返回 true。详细内容,请参阅前面的 wdinfootnote 和 wdinendnote 的说明。
  487.             //wdinheaderfooter 如果指定的所选内容或区域位于页眉或页脚窗格中,或者位于页面视图的页眉或页脚中,则本参数返回 true。
  488.             //wdinmasterdocument 如果指定的所选内容或区域位于主控文档中,则本参数返回 true。
  489.             //wdinwordmail 返回一个值,该值表明了所选内容或区域的的位置,如下表所示。值 位置
  490.             //0 所选内容或区域不在一条电子邮件消息中。
  491.             //1 所选内容或区域位于正在发送的电子邮件中。
  492.             //2 所选内容或区域位于正在阅读的电子邮件中。
  493.             //wdmaximumnumberofcolumns 返回所选内容或区域中任何行的最大表格列数。
  494.             //wdmaximumnumberofrows 返回指定的所选内容或区域中表格的最大行数。
  495.             //wdnumberofpagesindocument 返回与所选内容或区域相关联的文档的页数。
  496.             //wdnumlock 如果 num lock 有效,则本参数返回 true。
  497.             //wdovertype 如果改写模式有效,则本参数返回 true。可用 overtype 属性改变改写模式的状态。
  498.             //wdreferenceoftype 返回一个值,该值表明所选内容相对于脚注、尾注或批注引用的位置,如下表所示。 值 描述
  499.             //— 1 所选内容或区域包含、但不只限定于脚注、尾注或批注引用中。
  500.             //0 所选内容或区域不在脚注、尾注或批注引用之前。
  501.             //1 所选内容或区域位于脚注引用之前。
  502.             //2 所选内容或区域位于尾注引用之前。
  503.             //3 所选内容或区域位于批注引用之前。
  504.             //wdrevisionmarking 如果修订功能处于活动状态,则本参数返回 true。
  505.             //wdselectionmode 返回一个值,该值表明当前的选定模式,如下表所示。 值 选定模式
  506.             //0 常规选定
  507.             //1 扩展选定
  508.             //2 列选定
  509.             //wdstartofrangecolumnnumber 返回所选内容或区域的起点所在的表格的列号。
  510.             //wdstartofrangerownumber 返回所选内容或区域的起点所在的表格的行号。
  511.             //wdverticalpositionrelativetopage 返回所选内容或区域的垂直位置,即所选内容的上边与页面的上边之间的距离,以磅为单位。如果所选内容或区域没有显示在屏幕上,则本参数返回 - 1。
  512.             //wdverticalpositionrelativetotextboundary 返回所选内容或区域相对于周围最近的正文边界的上边的垂直位置,以磅为单位。如果所选内容或区域没有显示在屏幕上,则本参数返回 - 1。
  513.             //wdwithintable 如果所选内容位于一个表格中,则本参数返回 true。
  514.             //wdzoompercentage 返回由 percentage 属性设置的当前的放大百分比。
  515.             #endregion
  516.             #region 光标移动
  517.             //移动光标
  518.             //光标下移3行 上移3行
  519.             object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
  520.             object count = 3;
  521.             WordApp.Selection.MoveEnd( ref unit, ref count );
  522.             WordApp.Selection.MoveUp( ref unit, ref count, ref oMissing );
  523.             //Microsoft.Office.Interop.Word.WdUnits说明
  524.             //wdCell                  A cell.
  525.             //wdCharacter             A character.
  526.             //wdCharacterFormatting   Character formatting.
  527.             //wdColumn                A column.
  528.             //wdItem                  The selected item.
  529.             //wdLine                  A line. //行
  530.             //wdParagraph             A paragraph.
  531.             //wdParagraphFormatting   Paragraph formatting.
  532.             //wdRow                   A row.
  533.             //wdScreen                The screen dimensions.
  534.             //wdSection               A section.
  535.             //wdSentence              A sentence.
  536.             //wdStory                 A story.
  537.             //wdTable                 A table.
  538.             //wdWindow                A window.
  539.             //wdWord                  A word.
  540.             //录制的vb宏
  541.             //     ,移动光标至当前行首
  542.             //    Selection.HomeKey unit:=wdLine
  543.             //    '移动光标至当前行尾
  544.             //    Selection.EndKey unit:=wdLine
  545.             //    '选择从光标至当前行首的内容
  546.             //    Selection.HomeKey unit:=wdLine, Extend:=wdExtend
  547.             //    '选择从光标至当前行尾的内容
  548.             //    Selection.EndKey unit:=wdLine, Extend:=wdExtend
  549.             //    '选择当前行
  550.             //    Selection.HomeKey unit:=wdLine
  551.             //    Selection.EndKey unit:=wdLine, Extend:=wdExtend
  552.             //    '移动光标至文档开始
  553.             //    Selection.HomeKey unit:=wdStory
  554.             //    '移动光标至文档结尾
  555.             //    Selection.EndKey unit:=wdStory
  556.             //    '选择从光标至文档开始的内容
  557.             //    Selection.HomeKey unit:=wdStory, Extend:=wdExtend
  558.             //    '选择从光标至文档结尾的内容
  559.             //    Selection.EndKey unit:=wdStory, Extend:=wdExtend
  560.             //    '选择文档全部内容(从WholeStory可猜出Story应是当前文档的意思)
  561.             //    Selection.WholeStory
  562.             //    '移动光标至当前段落的开始
  563.             //    Selection.MoveUp unit:=wdParagraph
  564.             //    '移动光标至当前段落的结尾
  565.             //    Selection.MoveDown unit:=wdParagraph
  566.             //    '选择从光标至当前段落开始的内容
  567.             //    Selection.MoveUp unit:=wdParagraph, Extend:=wdExtend
  568.             //    '选择从光标至当前段落结尾的内容
  569.             //    Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend
  570.             //    '选择光标所在段落的内容
  571.             //    Selection.MoveUp unit:=wdParagraph
  572.             //    Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend
  573.             //    '显示选择区的开始与结束的位置,注意:文档第1个字符的位置是0
  574.             //    MsgBox ("第" > Selection.Start > "个字符至第" > Selection.End > "个字符")
  575.             //    '删除当前行
  576.             //    Selection.HomeKey unit:=wdLine
  577.             //    Selection.EndKey unit:=wdLine, Extend:=wdExtend
  578.             //    Selection.Delete
  579.             //    '删除当前段落
  580.             //    Selection.MoveUp unit:=wdParagraph
  581.             //    Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend
  582.             //    Selection.Delete
  583.             //表格的光标移动
  584.             //光标到当前光标所在表格的地单元格
  585.             WordApp.Selection.Tables[1].Cell( 1, 1 ).Select();
  586.             //unit对象定义
  587.             object unith = Microsoft.Office.Interop.Word.WdUnits.wdRow;//表格行方式
  588.             object extend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;/**//**//**////extend对光标移动区域进行扩展选择
  589.             object unitu = Microsoft.Office.Interop.Word.WdUnits.wdLine;//文档行方式,可以看成表格一行.不过和wdRow有区别
  590.             object unitp = Microsoft.Office.Interop.Word.WdUnits.wdParagraph;//段落方式,对于表格可以选择到表格行后的换车符,对于跨行合并的行选择,我能找到的最简单方式
  591.             //object count = 1;//光标移动量
  592.             #endregion
  593.         }
  594.         #endregion
  595.         #region 读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。
  596.         /**//// <summary>
  597.         /// 读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。
  598.         /// </summary>
  599.         /// <param name="fileName">word文档</param>
  600.         /// <param name="rowIndex">行</param>
  601.         /// <param name="colIndex">列</param>
  602.         /// <returns>返回数据</returns>
  603.         public static string ReadWord_tableContentByCell( string fileName, int rowIndex, int colIndex )
  604.         {
  605.             ApplicationClass cls = null;
  606.             Document doc = null;
  607.             Table table = null;
  608.             object missing = Missing.Value;
  609.             object path = fileName;
  610.             cls = new ApplicationClass();
  611.             try
  612.             {
  613.                 doc = cls.Documents.Open
  614.                   ( ref path, ref missing, ref missing, ref missing,
  615.                   ref missing, ref missing, ref missing, ref missing,
  616.                   ref missing, ref missing, ref missing, ref missing,
  617.                   ref missing, ref missing, ref missing, ref missing );
  618.                 table = doc.Tables[1];
  619.                 string text = table.Cell( rowIndex, colIndex ).Range.Text.ToString();
  620.                 text = text.Substring( 0, text.Length - 2 );  //去除尾部的mark
  621.                 return text;
  622.             }
  623.             catch( Exception ex )
  624.             {
  625.                 return ex.Message;
  626.             }
  627.             finally
  628.             {
  629.                 if( doc != null )
  630.                     doc.Close( ref missing, ref missing, ref missing );
  631.                 cls.Quit( ref missing, ref missing, ref missing );
  632.             }
  633.         }
  634.         #endregion
  635.  
  636.         #region 修改word表格中指定单元格的数据
  637.         /**//// <summary>
  638.         /// 修改word表格中指定单元格的数据
  639.         /// </summary>
  640.         /// <param name="fileName">word文档包括路径</param>
  641.         /// <param name="rowIndex">行</param>
  642.         /// <param name="colIndex">列</param>
  643.         /// <param name="content"></param>
  644.         /// <returns></returns>
  645.         public static bool UpdateWordTableByCell( string fileName, int rowIndex, int colIndex, string content )
  646.         {
  647.             ApplicationClass cls = null;
  648.             Document doc = null;
  649.             Table table = null;
  650.             object missing = Missing.Value;
  651.             object path = fileName;
  652.             cls = new ApplicationClass();
  653.             try
  654.             {
  655.                 doc = cls.Documents.Open
  656.                     ( ref path, ref missing, ref missing, ref missing,
  657.                   ref missing, ref missing, ref missing, ref missing,
  658.                   ref missing, ref missing, ref missing, ref missing,
  659.                   ref missing, ref missing, ref missing, ref missing );
  660.                 table = doc.Tables[1];
  661.                 //doc.Range( ref 0, ref 0 ).InsertParagraphAfter();//插入回车
  662.                 table.Cell( rowIndex, colIndex ).Range.InsertParagraphAfter();//.Text = content;
  663.                 return true;
  664.             }
  665.             catch
  666.             {
  667.                 return false;
  668.             }
  669.             finally
  670.             {
  671.                 if( doc != null )
  672.                 {
  673.                     doc.Close( ref missing, ref missing, ref missing );
  674.                     cls.Quit( ref missing, ref missing, ref missing );
  675.                 }
  676.             }
  677.         }
  678.         #endregion
  679.  
  680.         #region 清楚word进程
  681.         /**//// <summary>
  682.         /// 清楚word进程
  683.         /// </summary>
  684.         public static void KillWordProcess()
  685.         {
  686.             System.Diagnostics.Process[] myPs;
  687.             myPs = System.Diagnostics.Process.GetProcesses();
  688.             foreach( System.Diagnostics.Process p in myPs )
  689.             {
  690.                 if( p.Id != 0 )
  691.                 {
  692.                     string myS = "WINWORD.EXE" + p.ProcessName + "  ID:" + p.Id.ToString();
  693.                     try
  694.                     {
  695.                         if( p.Modules != null )
  696.                             if( p.Modules.Count > 0 )
  697.                             {
  698.                                 System.Diagnostics.ProcessModule pm = p.Modules[0];
  699.                                 myS += "/n Modules[0].FileName:" + pm.FileName;
  700.                                 myS += "/n Modules[0].ModuleName:" + pm.ModuleName;
  701.                                 myS += "/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString();
  702.                                 if( pm.ModuleName.ToLower() == "winword.exe" )
  703.                                     p.Kill();
  704.                             }
  705.                     }
  706.                     catch
  707.                     { }
  708.                     finally
  709.                     {
  710.  
  711.                     }
  712.                 }
  713.             }
  714.         }
  715.         #endregion
  716.  
  717.         #region 清楚excel进程
  718.         /**//// <summary>
  719.         /// 清楚excel进程
  720.         /// </summary>
  721.         public static void KillExcelProcess()
  722.         {
  723.             System.Diagnostics.Process[] myPs;
  724.             myPs = System.Diagnostics.Process.GetProcesses();
  725.             foreach( System.Diagnostics.Process p in myPs )
  726.             {
  727.                 if( p.Id != 0 )
  728.                 {
  729.                     string myS = "excel.EXE" + p.ProcessName + "  ID:" + p.Id.ToString();
  730.                     try
  731.                     {
  732.                         if( p.Modules != null )
  733.                             if( p.Modules.Count > 0 )
  734.                             {
  735.                                 System.Diagnostics.ProcessModule pm = p.Modules[0];
  736.                                 myS += "/n Modules[0].FileName:" + pm.FileName;
  737.                                 myS += "/n Modules[0].ModuleName:" + pm.ModuleName;
  738.                                 myS += "/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString();
  739.                                 if( pm.ModuleName.ToLower() == "excel.exe" )
  740.                                     p.Kill();
  741.                             }
  742.                     }
  743.                     catch
  744.                     { }
  745.                     finally
  746.                     {
  747.  
  748.                     }
  749.                 }
  750.             }
  751.         }
  752.         #endregion
  753.  
  754.         #region 网页内容或导入wordexcel
  755.         /**//// <summary>
  756.         /// 网页内容保存或导出为word或excel
  757.         /// </summary>
  758.         /// <param name="url">网页地址</param>
  759.         /// <param name="num">0为导出word,1为导出excel</param>
  760.         public static void SaveOrOutData( string url, int num )//导出数据的函数0为word,1为Excel
  761.         {
  762.             WebRequest req = WebRequest.Create( url );
  763.             WebResponse resp = req.GetResponse();
  764.             StreamReader sr = new StreamReader( resp.GetResponseStream(), System.Text.Encoding.UTF8 );
  765.             string x = sr.ReadToEnd();
  766.             System.Web.HttpContext.Current.Response.Clear();
  767.             System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding( "gb2312" );
  768.             string fName = DateTime.Now.ToString( "yyyy-MM-dd-ss" );
  769.             if( num == 0 )
  770.             {
  771.                 fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding( "gb2312" ) ) + ".doc";
  772.                 System.Web.HttpContext.Current.Response.ContentType = "application/ms-word";
  773.             }
  774.             else
  775.             {
  776.                 fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding( "gb2312" ) ) + ".xls";
  777.                 System.Web.HttpContext.Current.Response.ContentType = "application nd.xls";
  778.             }
  779.             System.Web.HttpContext.Current.Response.AddHeader( "content-disposition", "attachment;filename=" + fName );
  780.             System.Web.HttpContext.Current.Response.Write( getBodyContent( x ) );//获取table标签
  781.             System.Web.HttpContext.Current.Response.Flush();
  782.             System.Web.HttpContext.Current.Response.End();
  783.         }
  784.         /**//// <summary>
  785.         /// 获取网页table标签的内容
  786.         /// </summary>
  787.         /// <param name="input">html代码</param>
  788.         /// <returns></returns>
  789.         private static string getBodyContent( string input )
  790.         {
  791.             string pattern = @"<table.*?</table>";
  792.             Regex reg = new Regex( pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase );
  793.             Match mc = reg.Match( input );
  794.             string bodyContent = "";
  795.             if( mc.Success )
  796.             {
  797.                 bodyContent = mc.Value;
  798.             }
  799.             return bodyContent;
  800.         }
  801.         #endregion 
  802.  
  803.         #region 判断系统是否装excel
  804.         /**//// <summary>
  805.         /// 判断系统是否装excel
  806.         /// </summary>
  807.         /// <returns></returns>
  808.         public static bool IsInstallExcel()
  809.         {
  810.             RegistryKey machineKey = Registry.LocalMachine;
  811.             if( IsInstallExcelByVersion( "12.0", machineKey ) )
  812.             {
  813.                 return true;
  814.             }
  815.             if( IsInstallExcelByVersion( "11.0", machineKey ) )
  816.             {
  817.                 return true;
  818.             }
  819.             return false;
  820.         }
  821.         /**//// <summary>
  822.         /// 判断系统是否装某版本的excel
  823.         /// </summary>
  824.         /// <param name="strVersion">版本号</param>
  825.         /// <param name="machineKey"></param>
  826.         /// <returns></returns>
  827.         private static bool IsInstallExcelByVersion( string strVersion, RegistryKey machineKey )
  828.         {
  829.             try
  830.             {
  831.                 RegistryKey installKey = machineKey.OpenSubKey( "Software" ).OpenSubKey( "Microsoft" ).OpenSubKey( "Office" ).OpenSubKey( strVersion ).OpenSubKey( "Excel" ).OpenSubKey( "InstallRoot" );
  832.                 if( installKey == null )
  833.                 {
  834.                     return false;
  835.                 }
  836.                 return true;
  837.             }
  838.             catch
  839.             {
  840.                 return false;
  841.             }
  842.         }
  843.         #endregion
  844.  
  845.         #region 判断系统是否装word
  846.         /**//// <summary>
  847.         /// 判断系统是否装word
  848.         /// </summary>
  849.         /// <returns></returns>
  850.         public static bool IsInstallWord()
  851.         {
  852.             RegistryKey machineKey = Registry.LocalMachine;
  853.             if( IsInstallExcelByVersion( "12.0", machineKey ) )
  854.             {
  855.                 return true;
  856.             }
  857.             if( IsInstallExcelByVersion( "11.0", machineKey ) )
  858.             {
  859.                 return true;
  860.             }
  861.             return false;
  862.         }
  863.         /**//// <summary>
  864.         /// 判断系统是否装某版本的word
  865.         /// </summary>
  866.         /// <param name="strVersion">版本号</param>
  867.         /// <param name="machineKey"></param>
  868.         /// <returns></returns>
  869.         private static bool IsInstallWordByVersion( string strVersion, RegistryKey machineKey )
  870.         {
  871.             try
  872.             {
  873.                 RegistryKey installKey = machineKey.OpenSubKey( "Software" ).OpenSubKey( "Microsoft" ).OpenSubKey( "Office" ).OpenSubKey( strVersion ).OpenSubKey( "Word" ).OpenSubKey( "InstallRoot" );
  874.                 if( installKey == null )
  875.                 {
  876.                     return false;
  877.                 }
  878.                 return true;
  879.             }
  880.             catch
  881.             {
  882.                 return false;
  883.             }
  884.         }
  885.         #endregion              
  886.     }
  887. }
    1. using System;
    2. using System.Collections.Generic;
    3. using System.Text;
    4. using Microsoft.Office.Interop.Word;
    5. using System.IO;
    6. using System.Web;
    7. using System.Data;
    8. using System.Reflection;
    9. using Microsoft.Win32;
    10. using System.Text.RegularExpressions;
    11. using System.Net;
    12. namespace OfficeOperate
    13. {
    14.     public class WordOperate
    15.     {
    16.         #region 动态生成Word文档并填充数据
    17.         /**//// <summary>
    18.         /// 动态生成Word文档并填充数据
    19.         /// </summary>
    20.         /// <returns>返回自定义信息</returns>
    21.         public static string CreateWordFile()
    22.         {
    23.             string message = "";
    24.             try
    25.             {
    26.                 Object oMissing = System.Reflection.Missing.Value;
    27.                 string dir = System.Web.HttpContext.Current.Server.MapPath( "" );//首先在类库添加using System.web的引用
    28.                 if( !Directory.Exists( dir + "//file" ) )
    29.                 {
    30.                     Directory.CreateDirectory( dir + "//file" );  //创建文件所在目录
    31.                 }
    32.                 string name = DateTime.Now.ToLongDateString() + ".doc";
    33.                 object filename = dir + "//file//" + name;  //文件保存路径
    34.                 //创建Word文档
    35.                 Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    36.                 Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
    37.                 /**/////添加页眉方法一:
    38.                 //WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
    39.                 //WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
    40.                 //WordApp.ActiveWindow.ActivePane.Selection.InsertAfter( "无锡全真通科技有限公司" );//页眉内容
    41.                 //添加页眉方法二:
    42.                 if( WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdNormalView || WordApp.ActiveWindow.ActivePane.View.Type == Microsoft.Office.Interop.Word.WdViewType.wdOutlineView )
    43.                 {
    44.                     WordApp.ActiveWindow.ActivePane.View.Type = Microsoft.Office.Interop.Word.WdViewType.wdPrintView;
    45.                 }
    46.                 WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;
    47.                 string sHeader = "页眉内容";
    48.                 WordApp.Selection.HeaderFooter.LinkToPrevious = false;
    49.                 WordApp.Selection.HeaderFooter.Range.Text = sHeader;
    50.                 WordApp.ActiveWindow.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
    51.                 //WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐
    52.                 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;//设置左对齐  
    53.                 WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置
    54.                 WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距
    55.                 //移动焦点并换行
    56.                 object count = 14;
    57.                 object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行;
    58.                 WordApp.Selection.MoveDown( ref WdLine, ref count, ref oMissing );//移动焦点
    59.                 WordApp.Selection.TypeParagraph();//插入段落
    60.                 //文档中创建表格
    61.                 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add( WordApp.Selection.Range, 12, 3, ref oMissing, ref oMissing );
    62.                 //设置表格样式
    63.                 newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
    64.                 newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
    65.                 newTable.Columns[1].Width = 100f;
    66.                 newTable.Columns[2].Width = 220f;
    67.                 newTable.Columns[3].Width = 105f;
    68.                 //填充表格内容
    69.                 newTable.Cell( 1, 1 ).Range.Text = "产品详细信息表";
    70.                 newTable.Cell( 1, 1 ).Range.Bold = 2;//设置单元格中字体为粗体
    71.                 //合并单元格
    72.                 newTable.Cell( 1, 1 ).Merge( newTable.Cell( 1, 3 ) );
    73.                 WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
    74.                 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
    75.                 //填充表格内容
    76.                 newTable.Cell( 2, 1 ).Range.Text = "产品基本信息";
    77.                 newTable.Cell( 2, 1 ).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
    78.                 //合并单元格
    79.                 newTable.Cell( 2, 1 ).Merge( newTable.Cell( 2, 3 ) );
    80.                 WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
    81.                 //填充表格内容
    82.                 newTable.Cell( 3, 1 ).Range.Text = "品牌名称:";
    83.                 newTable.Cell( 3, 2 ).Range.Text = "BrandName";
    84.                 //纵向合并单元格
    85.                 newTable.Cell( 3, 3 ).Select();//选中一行
    86.                 object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
    87.                 object moveCount = 5;
    88.                 object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
    89.                 WordApp.Selection.MoveDown( ref moveUnit, ref moveCount, ref moveExtend );
    90.                 WordApp.Selection.Cells.Merge();
    91.                 //插入图片
    92.                 if( File.Exists( System.Web.HttpContext.Current.Server.MapPath( "images//picture.jpg" ) ) )
    93.                 {
    94.                     string FileName = System.Web.HttpContext.Current.Server.MapPath( "images//picture.jpg" );//图片所在路径
    95.                     object LinkToFile = false;
    96.                     object SaveWithDocument = true;
    97.                     object Anchor = WordDoc.Application.Selection.Range;
    98.                     WordDoc.Application.ActiveDocument.InlineShapes.AddPicture( FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor );
    99.                     WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度
    100.                     WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度
    101.                 }
    102.                 //将图片设置为四周环绕型
    103.                 Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
    104.                 s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;
    105.                 newTable.Cell( 12, 1 ).Range.Text = "产品特殊属性";
    106.                 newTable.Cell( 12, 1 ).Merge( newTable.Cell( 12, 3 ) );
    107.                 //在表格中增加行
    108.                 WordDoc.Content.Tables[1].Rows.Add( ref oMissing );
    109.                 WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();//“落款”
    110.                 WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
    111.                 //文件保存
    112.                 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 );
    113.                 WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );
    114.                 WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );
    115.                 message = name + "文档生成成功";
    116.             }
    117.             catch
    118.             {
    119.                 message = "文件导出异常!";
    120.             }
    121.             return message;
    122.         }
    123.         #endregion       
    124.         #region 创建并打开一个空的word文档进行编辑
    125.         /**//// <summary>
    126.         /// 创建并打开一个空的word文档进行编辑
    127.         /// </summary>
    128.         public static void OpenNewWordFileToEdit()
    129.         {
    130.             object oMissing = System.Reflection.Missing.Value;
    131.             Microsoft.Office.Interop.Word.Application WordApp;
    132.             Microsoft.Office.Interop.Word.Document WordDoc;
    133.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    134.             WordApp.Visible = true;
    135.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
    136.         }
    137.         #endregion
    138.         #region 创建word文档
    139.         /**//// <summary>
    140.         /// 创建word文档
    141.         /// </summary>
    142.         /// <returns></returns>
    143.         public static string createWord()
    144.         {
    145.             Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    146.             Document WordDoc;
    147.             string strContent = "";
    148.             object strFileName = System.Web.HttpContext.Current.Server.MapPath( "test.doc " );
    149.             if( System.IO.File.Exists( (string)strFileName ) )
    150.                 System.IO.File.Delete( (string)strFileName );
    151.             Object oMissing = System.Reflection.Missing.Value;
    152.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
    153.             #region   将数据库中读取得数据写入到word文件中
    154.             strContent = "你好/n/n/r ";
    155.             WordDoc.Paragraphs.Last.Range.Text = strContent;
    156.             strContent = "这是测试程序 ";
    157.             WordDoc.Paragraphs.Last.Range.Text = strContent;
    158.             #endregion
    159.             //将WordDoc文档对象的内容保存为DOC文档  
    160.             WordDoc.SaveAs( ref strFileName, 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 );
    161.             //关闭WordDoc文档对象  
    162.             WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );
    163.             //关闭WordApp组件对象  
    164.             WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );
    165.             string message = strFileName + "/r/n " + "创建成功 ";
    166.             return message;
    167.         }
    168.         #endregion
    169.         #region Word文档装化为Html文件
    170.         /**//// <summary>
    171.         /// 把Word文档装化为Html文件
    172.         /// </summary>
    173.         /// <param name="strFileName">要转换的Word文档</param>
    174.         public static void WordToHtml( string strFileName )
    175.         {
    176.             string saveFileName = strFileName + DateTime.Now.ToString( "yyyy-MM-dd-HH-mm-ss" ) + ".html";
    177.             WordToHtml( strFileName, saveFileName );
    178.         }
    179.         /**//// <summary>
    180.         /// 把Word文档装化为Html文件
    181.         /// </summary>
    182.         /// <param name="strFileName">要转换的Word文档</param>
    183.         /// <param name="strSaveFileName">要生成的具体的Html页面</param>
    184.         public static void WordToHtml( string strFileName, string strSaveFileName )
    185.         {
    186.             Microsoft.Office.Interop.Word.ApplicationClass WordApp;
    187.             Microsoft.Office.Interop.Word.Document WordDoc;
    188.             Object oMissing = System.Reflection.Missing.Value;
    189.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    190.             object fileName = strFileName;
    191.  
    192.             WordDoc = WordApp.Documents.Open( ref fileName,
    193.                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
    194.                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
    195.                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing );
    196.             Type wordType = WordApp.GetType();
    197.             // 打开文件
    198.             Type docsType = WordApp.Documents.GetType();
    199.             // 转换格式,另存为
    200.             Type docType = WordDoc.GetType();
    201.             object saveFileName = strSaveFileName;
    202.             docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, WordDoc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML } );
    203.             #region 其它格式:
    204.             /**//**/
    205.             /**////wdFormatHTML
    206.             ///wdFormatDocument
    207.             ///wdFormatDOSText
    208.             ///wdFormatDOSTextLineBreaks
    209.             ///wdFormatEncodedText
    210.             ///wdFormatRTF
    211.             ///wdFormatTemplate
    212.             ///wdFormatText
    213.             ///wdFormatTextLineBreaks
    214.             ///wdFormatUnicodeText
    215.             //--------------------------------------------------------------------------            //            docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod,
    216.             //                null, WordDoc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML} );
    217.             // 退出 Word
    218.             //wordType.InvokeMember( "Quit", System.Reflection.BindingFlags.InvokeMethod,
    219.             //    null, WordApp, null );
    220.             #endregion
    221.             WordDoc.Close( ref oMissing, ref oMissing, ref oMissing );
    222.             WordApp.Quit( ref oMissing, ref oMissing, ref oMissing );
    223.         }
    224.         #endregion
    225.         #region 导入模板
    226.         /**//// <summary>
    227.         /// 导入模板
    228.         /// </summary>
    229.         /// <param name="filePath">模板文档路径</param>
    230.         public static void ImportTemplate( string filePath )
    231.         {
    232.             object oMissing = System.Reflection.Missing.Value;
    233.             Microsoft.Office.Interop.Word.Application WordApp;
    234.             Microsoft.Office.Interop.Word.Document WordDoc;
    235.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    236.             WordApp.Visible = true;
    237.             object fileName = filePath;
    238.             WordDoc = WordApp.Documents.Add( ref fileName, ref oMissing, ref oMissing, ref oMissing );
    239.         }
    240.         #endregion
    241.         #region word中添加新表
    242.         /**//// <summary>
    243.         /// word中添加新表
    244.         /// </summary>
    245.         public static void AddTable()
    246.         {
    247.             object oMissing = System.Reflection.Missing.Value;
    248.             Microsoft.Office.Interop.Word.Application WordApp;
    249.             Microsoft.Office.Interop.Word.Document WordDoc;
    250.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    251.             WordApp.Visible = true;
    252.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
    253.             object start = 0;
    254.             object end = 0;
    255.             Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
    256.             WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );//3行4列的表
    257.         }
    258.         #endregion
    259.         #region 在表中插入新行
    260.         /**//// <summary>
    261.         /// 在表中插入新的1行
    262.         /// </summary>
    263.         public static void AddRow()
    264.         {
    265.             object oMissing = System.Reflection.Missing.Value;
    266.             Microsoft.Office.Interop.Word.Application WordApp;
    267.             Microsoft.Office.Interop.Word.Document WordDoc;
    268.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    269.             WordApp.Visible = true;
    270.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
    271.             object start = 0;
    272.             object end = 0;
    273.             Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
    274.             WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );
    275.             Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
    276.             object beforeRow = newTable.Rows[1];
    277.             newTable.Rows.Add( ref beforeRow );
    278.         }
    279.         #endregion
    280.         #region 分离单元格
    281.         /**//// <summary>
    282.         /// 合并单元格
    283.         /// </summary>
    284.         public static void CombinationCell()
    285.         {
    286.             object oMissing = System.Reflection.Missing.Value;
    287.             Microsoft.Office.Interop.Word.Application WordApp;
    288.             Microsoft.Office.Interop.Word.Document WordDoc;
    289.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    290.             WordApp.Visible = true;
    291.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
    292.             object start = 0;
    293.             object end = 0;
    294.             Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
    295.             WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );
    296.             Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
    297.             object beforeRow = newTable.Rows[1];
    298.             newTable.Rows.Add( ref beforeRow );
    299.             Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 2, 1 );//2行1列合并2行2列为一起
    300.             cell.Merge( newTable.Cell( 2, 2 ) );
    301.             //cell.Merge( newTable.Cell( 1, 3 ) );
    302.         }
    303.         #endregion
    304.         #region 分离单元格
    305.         /**//// <summary>
    306.         /// 分离单元格
    307.         /// </summary>
    308.         public static void SeparateCell()
    309.         {
    310.             object oMissing = System.Reflection.Missing.Value;
    311.             Microsoft.Office.Interop.Word.Application WordApp;
    312.             Microsoft.Office.Interop.Word.Document WordDoc;
    313.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    314.             WordApp.Visible = true;
    315.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
    316.             object start = 0;
    317.             object end = 0;
    318.             Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range( ref start, ref end );
    319.             WordDoc.Tables.Add( tableLocation, 3, 4, ref oMissing, ref oMissing );
    320.             Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1];
    321.             object beforeRow = newTable.Rows[1];
    322.             newTable.Rows.Add( ref beforeRow );
    323.             Microsoft.Office.Interop.Word.Cell cell = newTable.Cell( 1, 1 );
    324.             cell.Merge( newTable.Cell( 1, 2 ) );
    325.             object Rownum = 2;
    326.             object Columnnum = 2;
    327.             cell.Split( ref Rownum, ref  Columnnum );
    328.         }
    329.         #endregion
    330.         #region 通过段落控制插入Insert a paragraph at the beginning of the document.
    331.         /**//// <summary>
    332.         /// 通过段落控制插入Insert a paragraph at the beginning of the document.
    333.         /// </summary>
    334.         public static void Insert()
    335.         {
    336.             object oMissing = System.Reflection.Missing.Value;
    337.             //object oEndOfDoc = "//endofdoc"; /**//* /endofdoc is a predefined bookmark */
    338.             //Start Word and create a new document.
    339.             Microsoft.Office.Interop.Word.Application WordApp;
    340.             Microsoft.Office.Interop.Word.Document WordDoc;
    341.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    342.             WordApp.Visible = true;
    343.             WordDoc = WordApp.Documents.Add( ref oMissing, ref oMissing, ref oMissing, ref oMissing );
    344.             //Insert a paragraph at the beginning of the document.
    345.             Microsoft.Office.Interop.Word.Paragraph oPara1;
    346.             oPara1 = WordDoc.Content.Paragraphs.Add( ref oMissing );
    347.             oPara1.Range.Text = "Heading 1";
    348.             oPara1.Range.Font.Bold = 1;
    349.             oPara1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.
    350.             oPara1.Range.InsertParagraphAfter();
    351.         }
    352.         #endregion
    353.         #region word文档设置及获取光标位置
    354.         /**//// <summary>
    355.         /// word文档设置及获取光标位置
    356.         /// </summary>
    357.         public static void WordSet()
    358.         {
    359.             object oMissing = System.Reflection.Missing.Value;
    360.             Microsoft.Office.Interop.Word.Application WordApp;
    361.             Microsoft.Office.Interop.Word.Document WordDoc;
    362.             WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
    363.             #region 文档格式设置
    364.             WordApp.ActiveDocument.PageSetup.LineNumbering.Active = 0;//行编号
    365.             WordApp.ActiveDocument.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;//页面方向
    366.             WordApp.ActiveDocument.PageSetup.TopMargin = WordApp.CentimetersToPoints( float.Parse( "2.54" ) );//上页边距
    367.             WordApp.ActiveDocument.PageSetup.BottomMargin = WordApp.CentimetersToPoints( float.Parse( "2.54" ) );//下页边距
    368.             WordApp.ActiveDocument.PageSetup.LeftMargin = WordApp.CentimetersToPoints( float.Parse( "3.17" ) );//左页边距
    369.             WordApp.ActiveDocument.PageSetup.RightMargin = WordApp.CentimetersToPoints( float.Parse( "3.17" ) );//右页边距
    370.             WordApp.ActiveDocument.PageSetup.Gutter = WordApp.CentimetersToPoints( float.Parse( "0" ) );//装订线位置
    371.             WordApp.ActiveDocument.PageSetup.HeaderDistance = WordApp.CentimetersToPoints( float.Parse( "1.5" ) );//页眉
    372.             WordApp.ActiveDocument.PageSetup.FooterDistance = WordApp.CentimetersToPoints( float.Parse( "1.75" ) );//页脚
    373.             WordApp.ActiveDocument.PageSetup.PageWidth = WordApp.CentimetersToPoints( float.Parse( "21" ) );//纸张宽度
    374.             WordApp.ActiveDocument.PageSetup.PageHeight = WordApp.CentimetersToPoints( float.Parse( "29.7" ) );//纸张高度
    375.             WordApp.ActiveDocument.PageSetup.FirstPageTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源
    376.             WordApp.ActiveDocument.PageSetup.OtherPagesTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源
    377.             WordApp.ActiveDocument.PageSetup.SectionStart = Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage;//节的起始位置:新建页
    378.             WordApp.ActiveDocument.PageSetup.OddAndEvenPagesHeaderFooter = 0;//页眉页脚-奇偶页不同
    379.             WordApp.ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = 0;//页眉页脚-首页不同
    380.             WordApp.ActiveDocument.PageSetup.VerticalAlignment = Microsoft.Office.Interop.Word.WdVerticalAlignment.wdAlignVerticalTop;//页面垂直对齐方式
    381.             WordApp.ActiveDocument.PageSetup.SuppressEndnotes = 0;//不隐藏尾注
    382.             WordApp.ActiveDocument.PageSetup.MirrorMargins = 0;//不设置首页的内外边距
    383.             WordApp.ActiveDocument.PageSetup.TwoPagesOnOne = false;//不双面打印
    384.             WordApp.ActiveDocument.PageSetup.BookFoldPrinting = false;//不设置手动双面正面打印
    385.             WordApp.ActiveDocument.PageSetup.BookFoldRevPrinting = false;//不设置手动双面背面打印
    386.             WordApp.ActiveDocument.PageSetup.BookFoldPrintingSheets = 1;//打印默认份数
    387.             WordApp.ActiveDocument.PageSetup.GutterPos = Microsoft.Office.Interop.Word.WdGutterStyle.wdGutterPosLeft;//装订线位于左侧
    388.             WordApp.ActiveDocument.PageSetup.LinesPage = 40;//默认页行数量
    389.             WordApp.ActiveDocument.PageSetup.LayoutMode = Microsoft.Office.Interop.Word.WdLayoutMode.wdLayoutModeLineGrid;//版式模式为“只指定行网格”
    390.             #endregion
    391.             #region 段落格式设定
    392.             WordApp.Selection.ParagraphFormat.LeftIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//左缩进
    393.             WordApp.Selection.ParagraphFormat.RightIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//右缩进
    394.             WordApp.Selection.ParagraphFormat.SpaceBefore = float.Parse( "0" );//段前间距
    395.             WordApp.Selection.ParagraphFormat.SpaceBeforeAuto = 0;//
    396.             WordApp.Selection.ParagraphFormat.SpaceAfter = float.Parse( "0" );//段后间距
    397.             WordApp.Selection.ParagraphFormat.SpaceAfterAuto = 0;//
    398.             WordApp.Selection.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;//单倍行距
    399.             WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;//段落2端对齐
    400.             WordApp.Selection.ParagraphFormat.WidowControl = 0;//孤行控制
    401.             WordApp.Selection.ParagraphFormat.KeepWithNext = 0;//与下段同页
    402.             WordApp.Selection.ParagraphFormat.KeepTogether = 0;//段中不分页
    403.             WordApp.Selection.ParagraphFormat.PageBreakBefore = 0;//段前分页
    404.             WordApp.Selection.ParagraphFormat.NoLineNumber = 0;//取消行号
    405.             WordApp.Selection.ParagraphFormat.Hyphenation = 1;//取消段字
    406.             WordApp.Selection.ParagraphFormat.FirstLineIndent = WordApp.CentimetersToPoints( float.Parse( "0" ) );//首行缩进
    407.             WordApp.Selection.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevelBodyText;
    408.             WordApp.Selection.ParagraphFormat.CharacterUnitLeftIndent = float.Parse( "0" );
    409.             WordApp.Selection.ParagraphFormat.CharacterUnitRightIndent = float.Parse( "0" );
    410.             WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = float.Parse( "0" );
    411.             WordApp.Selection.ParagraphFormat.LineUnitBefore = float.Parse( "0" );
    412.             WordApp.Selection.ParagraphFormat.LineUnitAfter = float.Parse( "0" );
    413.             WordApp.Selection.ParagraphFormat.AutoAdjustRightIndent = 1;
    414.             WordApp.Selection.ParagraphFormat.DisableLineHeightGrid = 0;
    415.             WordApp.Selection.ParagraphFormat.FarEastLineBreakControl = 1;
    416.             WordApp.Selection.ParagraphFormat.WordWrap = 1;
    417.             WordApp.Selection.ParagraphFormat.HangingPunctuation = 1;
    418.             WordApp.Selection.ParagraphFormat.HalfWidthPunctuationOnTopOfLine = 0;
    419.             WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndAlpha = 1;
    420.             WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 1;
    421.             WordApp.Selection.ParagraphFormat.BaseLineAlignment = Microsoft.Office.Interop.Word.WdBaselineAlignment.wdBaselineAlignAuto;
    422.             #endregion
    423.             #region 字体格式设定
    424.             WordApp.Selection.Font.NameFarEast = "华文中宋";
    425.             WordApp.Selection.Font.NameAscii = "Times New Roman";
    426.             WordApp.Selection.Font.NameOther = "Times New Roman";
    427.             WordApp.Selection.Font.Name = "宋体";
    428.             WordApp.Selection.Font.Size = float.Parse( "14" );
    429.             WordApp.Selection.Font.Bold = 0;
    430.             WordApp.Selection.Font.Italic = 0;
    431.             WordApp.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;
    432.             WordApp.Selection.Font.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
    433.             WordApp.Selection.Font.StrikeThrough = 0;//删除线
    434.             WordApp.Selection.Font.DoubleStrikeThrough = 0;//双删除线
    435.             WordApp.Selection.Font.Outline = 0;//空心
    436.             WordApp.Selection.Font.Emboss = 0;//阳文
    437.             WordApp.Selection.Font.Shadow = 0;//阴影
    438.             WordApp.Selection.Font.Hidden = 0;//隐藏文字
    439.             WordApp.Selection.Font.SmallCaps = 0;//小型大写字母
    440.             WordApp.Selection.Font.AllCaps = 0;//全部大写字母
    441.             WordApp.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
    442.             WordApp.Selection.Font.Engrave = 0;//阴文
    443.             WordApp.Selection.Font.Superscript = 0;//上标
    444.             WordApp.Selection.Font.Subscript = 0;//下标
    445.             WordApp.Selection.Font.Spacing = float.Parse( "0" );//字符间距
    446.             WordApp.Selection.Font.Scaling = 100;//字符缩放
    447.             WordApp.Selection.Font.Position = 0;//位置
    448.             WordApp.Selection.Font.Kerning = float.Parse( "1" );//字体间距调整
    449.             WordApp.Selection.Font.Animation = Microsoft.Office.Interop.Word.WdAnimation.wdAnimationNone;//文字效果
    450.             WordApp.Selection.Font.DisableCharacterSpaceGrid = false;
    451.             WordApp.Selection.Font.EmphasisMark = Microsoft.Office.Interop.Word.WdEmphasisMark.wdEmphasisMarkNone;
    452.             #endregion
    453.             #region 获取光标位置
    454.             /**/////get_Information
    455.             WordApp.Selection.get_Information( WdInformation.wdActiveEndPageNumber );
    456.             //关于行号-页号-列号-位置
    457.             //information 属性
    458.             //返回有关指定的所选内容或区域的信息。variant 类型,只读。
    459.             //expression.information(type)
    460.             //expression 必需。该表达式返回一个 range 或 selection 对象。
    461.             //type long 类型,必需。需要返回的信息。可取下列 wdinformation 常量之一:
    462.             //wdactiveendadjustedpagenumber 返回页码,在该页中包含指定的所选内容或区域的活动结尾。如果设置了一个起始页码,并对页码进行了手工调整,则返回调整过的页码。
    463.             //wdactiveendpagenumber 返回页码,在该页中包含指定的所选内容或区域的活动结尾,页码从文档的开头开始计算而不考虑对页码的任何手工调整。
    464.             //wdactiveendsectionnumber 返回节号,在该节中包含了指定的所选内容或区域的活动结尾。
    465.             //wdatendofrowmarker 如果指定的所选内容或区域位于表格的行结尾标记处,则本参数返回 true。
    466.             //wdcapslock 如果大写字母锁定模式有效,则本参数返回 true。
    467.             //wdendofrangecolumnnumber 返回表格列号,在该表格列中包含了指定的所选内容或区域的活动结尾。
    468.             //wdendofrangerownumber 返回表格行号,在该表格行包含了指定的所选内容或区域的活动结尾。
    469.             //wdfirstcharactercolumnnumber 返回指定的所选内容或区域中第一个字符的位置。如果所选内容或区域是折叠的,则返回所选内容或区域右侧紧接着的字符编号。
    470.             //wdfirstcharacterlinenumber 返回所选内容中第一个字符的行号。如果 pagination 属性为 false,或 draft 属性为 true,则返回 - 1。
    471.             //wdframeisselected 如果所选内容或区域是一个完整的图文框文本框,则本参数返回 true。
    472.             //wdheaderfootertype 返回一个值,该值表明包含了指定的所选内容或区域的页眉或页脚的类型,如下表所示。 值 页眉或页脚的类型
    473.             //- 1 无
    474.             //0 偶数页页眉
    475.             //1 奇数页页眉
    476.             //2 偶数页页脚
    477.             //3 奇数页页脚
    478.             //4 第一个页眉
    479.             //5 第一个页脚
    480.             //wdhorizontalpositionrelativetopage 返回指定的所选内容或区域的水平位置。该位置是所选内容或区域的左边与页面的左边之间的距离,以磅为单位。如果所选内容或区域不可见,则返回 - 1。
    481.             //wdhorizontalpositionrelativetotextboundary 返回指定的所选内容或区域相对于周围最近的正文边界的左边的水平位置,以磅为单位。如果所选内容或区域没有显示在当前屏幕,则本参数返回 - 1。
    482.             //wdinclipboard 有关此常量的详细内容,请参阅 microsoft office 98 macintosh 版的语言参考帮助。
    483.             //wdincommentpane 如果指定的所选内容或区域位于批注窗格,则返回 true。
    484.             //wdinendnote 如果指定的所选内容或区域位于页面视图的尾注区内,或者位于普通视图的尾注窗格中,则本参数返回 true。
    485.             //wdinfootnote 如果指定的所选内容或区域位于页面视图的脚注区内,或者位于普通视图的脚注窗格中,则本参数返回 true。
    486.             //wdinfootnoteendnotepane 如果指定的所选内容或区域位于页面视图的脚注或尾注区内,或者位于普通视图的脚注或尾注窗格中,则本参数返回 true。详细内容,请参阅前面的 wdinfootnote 和 wdinendnote 的说明。
    487.             //wdinheaderfooter 如果指定的所选内容或区域位于页眉或页脚窗格中,或者位于页面视图的页眉或页脚中,则本参数返回 true。
    488.             //wdinmasterdocument 如果指定的所选内容或区域位于主控文档中,则本参数返回 true。
    489.             //wdinwordmail 返回一个值,该值表明了所选内容或区域的的位置,如下表所示。值 位置
    490.             //0 所选内容或区域不在一条电子邮件消息中。
    491.             //1 所选内容或区域位于正在发送的电子邮件中。
    492.             //2 所选内容或区域位于正在阅读的电子邮件中。
    493.             //wdmaximumnumberofcolumns 返回所选内容或区域中任何行的最大表格列数。
    494.             //wdmaximumnumberofrows 返回指定的所选内容或区域中表格的最大行数。
    495.             //wdnumberofpagesindocument 返回与所选内容或区域相关联的文档的页数。
    496.             //wdnumlock 如果 num lock 有效,则本参数返回 true。
    497.             //wdovertype 如果改写模式有效,则本参数返回 true。可用 overtype 属性改变改写模式的状态。
    498.             //wdreferenceoftype 返回一个值,该值表明所选内容相对于脚注、尾注或批注引用的位置,如下表所示。 值 描述
    499.             //— 1 所选内容或区域包含、但不只限定于脚注、尾注或批注引用中。
    500.             //0 所选内容或区域不在脚注、尾注或批注引用之前。
    501.             //1 所选内容或区域位于脚注引用之前。
    502.             //2 所选内容或区域位于尾注引用之前。
    503.             //3 所选内容或区域位于批注引用之前。
    504.             //wdrevisionmarking 如果修订功能处于活动状态,则本参数返回 true。
    505.             //wdselectionmode 返回一个值,该值表明当前的选定模式,如下表所示。 值 选定模式
    506.             //0 常规选定
    507.             //1 扩展选定
    508.             //2 列选定
    509.             //wdstartofrangecolumnnumber 返回所选内容或区域的起点所在的表格的列号。
    510.             //wdstartofrangerownumber 返回所选内容或区域的起点所在的表格的行号。
    511.             //wdverticalpositionrelativetopage 返回所选内容或区域的垂直位置,即所选内容的上边与页面的上边之间的距离,以磅为单位。如果所选内容或区域没有显示在屏幕上,则本参数返回 - 1。
    512.             //wdverticalpositionrelativetotextboundary 返回所选内容或区域相对于周围最近的正文边界的上边的垂直位置,以磅为单位。如果所选内容或区域没有显示在屏幕上,则本参数返回 - 1。
    513.             //wdwithintable 如果所选内容位于一个表格中,则本参数返回 true。
    514.             //wdzoompercentage 返回由 percentage 属性设置的当前的放大百分比。
    515.             #endregion
    516.             #region 光标移动
    517.             //移动光标
    518.             //光标下移3行 上移3行
    519.             object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
    520.             object count = 3;
    521.             WordApp.Selection.MoveEnd( ref unit, ref count );
    522.             WordApp.Selection.MoveUp( ref unit, ref count, ref oMissing );
    523.             //Microsoft.Office.Interop.Word.WdUnits说明
    524.             //wdCell                  A cell.
    525.             //wdCharacter             A character.
    526.             //wdCharacterFormatting   Character formatting.
    527.             //wdColumn                A column.
    528.             //wdItem                  The selected item.
    529.             //wdLine                  A line. //行
    530.             //wdParagraph             A paragraph.
    531.             //wdParagraphFormatting   Paragraph formatting.
    532.             //wdRow                   A row.
    533.             //wdScreen                The screen dimensions.
    534.             //wdSection               A section.
    535.             //wdSentence              A sentence.
    536.             //wdStory                 A story.
    537.             //wdTable                 A table.
    538.             //wdWindow                A window.
    539.             //wdWord                  A word.
    540.             //录制的vb宏
    541.             //     ,移动光标至当前行首
    542.             //    Selection.HomeKey unit:=wdLine
    543.             //    '移动光标至当前行尾
    544.             //    Selection.EndKey unit:=wdLine
    545.             //    '选择从光标至当前行首的内容
    546.             //    Selection.HomeKey unit:=wdLine, Extend:=wdExtend
    547.             //    '选择从光标至当前行尾的内容
    548.             //    Selection.EndKey unit:=wdLine, Extend:=wdExtend
    549.             //    '选择当前行
    550.             //    Selection.HomeKey unit:=wdLine
    551.             //    Selection.EndKey unit:=wdLine, Extend:=wdExtend
    552.             //    '移动光标至文档开始
    553.             //    Selection.HomeKey unit:=wdStory
    554.             //    '移动光标至文档结尾
    555.             //    Selection.EndKey unit:=wdStory
    556.             //    '选择从光标至文档开始的内容
    557.             //    Selection.HomeKey unit:=wdStory, Extend:=wdExtend
    558.             //    '选择从光标至文档结尾的内容
    559.             //    Selection.EndKey unit:=wdStory, Extend:=wdExtend
    560.             //    '选择文档全部内容(从WholeStory可猜出Story应是当前文档的意思)
    561.             //    Selection.WholeStory
    562.             //    '移动光标至当前段落的开始
    563.             //    Selection.MoveUp unit:=wdParagraph
    564.             //    '移动光标至当前段落的结尾
    565.             //    Selection.MoveDown unit:=wdParagraph
    566.             //    '选择从光标至当前段落开始的内容
    567.             //    Selection.MoveUp unit:=wdParagraph, Extend:=wdExtend
    568.             //    '选择从光标至当前段落结尾的内容
    569.             //    Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend
    570.             //    '选择光标所在段落的内容
    571.             //    Selection.MoveUp unit:=wdParagraph
    572.             //    Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend
    573.             //    '显示选择区的开始与结束的位置,注意:文档第1个字符的位置是0
    574.             //    MsgBox ("第" > Selection.Start > "个字符至第" > Selection.End > "个字符")
    575.             //    '删除当前行
    576.             //    Selection.HomeKey unit:=wdLine
    577.             //    Selection.EndKey unit:=wdLine, Extend:=wdExtend
    578.             //    Selection.Delete
    579.             //    '删除当前段落
    580.             //    Selection.MoveUp unit:=wdParagraph
    581.             //    Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend
    582.             //    Selection.Delete
    583.             //表格的光标移动
    584.             //光标到当前光标所在表格的地单元格
    585.             WordApp.Selection.Tables[1].Cell( 1, 1 ).Select();
    586.             //unit对象定义
    587.             object unith = Microsoft.Office.Interop.Word.WdUnits.wdRow;//表格行方式
    588.             object extend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;/**//**//**////extend对光标移动区域进行扩展选择
    589.             object unitu = Microsoft.Office.Interop.Word.WdUnits.wdLine;//文档行方式,可以看成表格一行.不过和wdRow有区别
    590.             object unitp = Microsoft.Office.Interop.Word.WdUnits.wdParagraph;//段落方式,对于表格可以选择到表格行后的换车符,对于跨行合并的行选择,我能找到的最简单方式
    591.             //object count = 1;//光标移动量
    592.             #endregion
    593.         }
    594.         #endregion
    595.         #region 读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。
    596.         /**//// <summary>
    597.         /// 读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。
    598.         /// </summary>
    599.         /// <param name="fileName">word文档</param>
    600.         /// <param name="rowIndex">行</param>
    601.         /// <param name="colIndex">列</param>
    602.         /// <returns>返回数据</returns>
    603.         public static string ReadWord_tableContentByCell( string fileName, int rowIndex, int colIndex )
    604.         {
    605.             ApplicationClass cls = null;
    606.             Document doc = null;
    607.             Table table = null;
    608.             object missing = Missing.Value;
    609.             object path = fileName;
    610.             cls = new ApplicationClass();
    611.             try
    612.             {
    613.                 doc = cls.Documents.Open
    614.                   ( ref path, ref missing, ref missing, ref missing,
    615.                   ref missing, ref missing, ref missing, ref missing,
    616.                   ref missing, ref missing, ref missing, ref missing,
    617.                   ref missing, ref missing, ref missing, ref missing );
    618.                 table = doc.Tables[1];
    619.                 string text = table.Cell( rowIndex, colIndex ).Range.Text.ToString();
    620.                 text = text.Substring( 0, text.Length - 2 );  //去除尾部的mark
    621.                 return text;
    622.             }
    623.             catch( Exception ex )
    624.             {
    625.                 return ex.Message;
    626.             }
    627.             finally
    628.             {
    629.                 if( doc != null )
    630.                     doc.Close( ref missing, ref missing, ref missing );
    631.                 cls.Quit( ref missing, ref missing, ref missing );
    632.             }
    633.         }
    634.         #endregion
    635.  
    636.         #region 修改word表格中指定单元格的数据
    637.         /**//// <summary>
    638.         /// 修改word表格中指定单元格的数据
    639.         /// </summary>
    640.         /// <param name="fileName">word文档包括路径</param>
    641.         /// <param name="rowIndex">行</param>
    642.         /// <param name="colIndex">列</param>
    643.         /// <param name="content"></param>
    644.         /// <returns></returns>
    645.         public static bool UpdateWordTableByCell( string fileName, int rowIndex, int colIndex, string content )
    646.         {
    647.             ApplicationClass cls = null;
    648.             Document doc = null;
    649.             Table table = null;
    650.             object missing = Missing.Value;
    651.             object path = fileName;
    652.             cls = new ApplicationClass();
    653.             try
    654.             {
    655.                 doc = cls.Documents.Open
    656.                     ( ref path, ref missing, ref missing, ref missing,
    657.                   ref missing, ref missing, ref missing, ref missing,
    658.                   ref missing, ref missing, ref missing, ref missing,
    659.                   ref missing, ref missing, ref missing, ref missing );
    660.                 table = doc.Tables[1];
    661.                 //doc.Range( ref 0, ref 0 ).InsertParagraphAfter();//插入回车
    662.                 table.Cell( rowIndex, colIndex ).Range.InsertParagraphAfter();//.Text = content;
    663.                 return true;
    664.             }
    665.             catch
    666.             {
    667.                 return false;
    668.             }
    669.             finally
    670.             {
    671.                 if( doc != null )
    672.                 {
    673.                     doc.Close( ref missing, ref missing, ref missing );
    674.                     cls.Quit( ref missing, ref missing, ref missing );
    675.                 }
    676.             }
    677.         }
    678.         #endregion
    679.  
    680.         #region 清楚word进程
    681.         /**//// <summary>
    682.         /// 清楚word进程
    683.         /// </summary>
    684.         public static void KillWordProcess()
    685.         {
    686.             System.Diagnostics.Process[] myPs;
    687.             myPs = System.Diagnostics.Process.GetProcesses();
    688.             foreach( System.Diagnostics.Process p in myPs )
    689.             {
    690.                 if( p.Id != 0 )
    691.                 {
    692.                     string myS = "WINWORD.EXE" + p.ProcessName + "  ID:" + p.Id.ToString();
    693.                     try
    694.                     {
    695.                         if( p.Modules != null )
    696.                             if( p.Modules.Count > 0 )
    697.                             {
    698.                                 System.Diagnostics.ProcessModule pm = p.Modules[0];
    699.                                 myS += "/n Modules[0].FileName:" + pm.FileName;
    700.                                 myS += "/n Modules[0].ModuleName:" + pm.ModuleName;
    701.                                 myS += "/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString();
    702.                                 if( pm.ModuleName.ToLower() == "winword.exe" )
    703.                                     p.Kill();
    704.                             }
    705.                     }
    706.                     catch
    707.                     { }
    708.                     finally
    709.                     {
    710.  
    711.                     }
    712.                 }
    713.             }
    714.         }
    715.         #endregion
    716.  
    717.         #region 清楚excel进程
    718.         /**//// <summary>
    719.         /// 清楚excel进程
    720.         /// </summary>
    721.         public static void KillExcelProcess()
    722.         {
    723.             System.Diagnostics.Process[] myPs;
    724.             myPs = System.Diagnostics.Process.GetProcesses();
    725.             foreach( System.Diagnostics.Process p in myPs )
    726.             {
    727.                 if( p.Id != 0 )
    728.                 {
    729.                     string myS = "excel.EXE" + p.ProcessName + "  ID:" + p.Id.ToString();
    730.                     try
    731.                     {
    732.                         if( p.Modules != null )
    733.                             if( p.Modules.Count > 0 )
    734.                             {
    735.                                 System.Diagnostics.ProcessModule pm = p.Modules[0];
    736.                                 myS += "/n Modules[0].FileName:" + pm.FileName;
    737.                                 myS += "/n Modules[0].ModuleName:" + pm.ModuleName;
    738.                                 myS += "/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString();
    739.                                 if( pm.ModuleName.ToLower() == "excel.exe" )
    740.                                     p.Kill();
    741.                             }
    742.                     }
    743.                     catch
    744.                     { }
    745.                     finally
    746.                     {
    747.  
    748.                     }
    749.                 }
    750.             }
    751.         }
    752.         #endregion
    753.  
    754.         #region 网页内容或导入wordexcel
    755.         /**//// <summary>
    756.         /// 网页内容保存或导出为word或excel
    757.         /// </summary>
    758.         /// <param name="url">网页地址</param>
    759.         /// <param name="num">0为导出word,1为导出excel</param>
    760.         public static void SaveOrOutData( string url, int num )//导出数据的函数0为word,1为Excel
    761.         {
    762.             WebRequest req = WebRequest.Create( url );
    763.             WebResponse resp = req.GetResponse();
    764.             StreamReader sr = new StreamReader( resp.GetResponseStream(), System.Text.Encoding.UTF8 );
    765.             string x = sr.ReadToEnd();
    766.             System.Web.HttpContext.Current.Response.Clear();
    767.             System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding( "gb2312" );
    768.             string fName = DateTime.Now.ToString( "yyyy-MM-dd-ss" );
    769.             if( num == 0 )
    770.             {
    771.                 fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding( "gb2312" ) ) + ".doc";
    772.                 System.Web.HttpContext.Current.Response.ContentType = "application/ms-word";
    773.             }
    774.             else
    775.             {
    776.                 fName = HttpUtility.UrlEncode( fName, System.Text.Encoding.GetEncoding( "gb2312" ) ) + ".xls";
    777.                 System.Web.HttpContext.Current.Response.ContentType = "application nd.xls";
    778.             }
    779.             System.Web.HttpContext.Current.Response.AddHeader( "content-disposition", "attachment;filename=" + fName );
    780.             System.Web.HttpContext.Current.Response.Write( getBodyContent( x ) );//获取table标签
    781.             System.Web.HttpContext.Current.Response.Flush();
    782.             System.Web.HttpContext.Current.Response.End();
    783.         }
    784.         /**//// <summary>
    785.         /// 获取网页table标签的内容
    786.         /// </summary>
    787.         /// <param name="input">html代码</param>
    788.         /// <returns></returns>
    789.         private static string getBodyContent( string input )
    790.         {
    791.             string pattern = @"<table.*?</table>";
    792.             Regex reg = new Regex( pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase );
    793.             Match mc = reg.Match( input );
    794.             string bodyContent = "";
    795.             if( mc.Success )
    796.             {
    797.                 bodyContent = mc.Value;
    798.             }
    799.             return bodyContent;
    800.         }
    801.         #endregion 
    802.  
    803.         #region 判断系统是否装excel
    804.         /**//// <summary>
    805.         /// 判断系统是否装excel
    806.         /// </summary>
    807.         /// <returns></returns>
    808.         public static bool IsInstallExcel()
    809.         {
    810.             RegistryKey machineKey = Registry.LocalMachine;
    811.             if( IsInstallExcelByVersion( "12.0", machineKey ) )
    812.             {
    813.                 return true;
    814.             }
    815.             if( IsInstallExcelByVersion( "11.0", machineKey ) )
    816.             {
    817.                 return true;
    818.             }
    819.             return false;
    820.         }
    821.         /**//// <summary>
    822.         /// 判断系统是否装某版本的excel
    823.         /// </summary>
    824.         /// <param name="strVersion">版本号</param>
    825.         /// <param name="machineKey"></param>
    826.         /// <returns></returns>
    827.         private static bool IsInstallExcelByVersion( string strVersion, RegistryKey machineKey )
    828.         {
    829.             try
    830.             {
    831.                 RegistryKey installKey = machineKey.OpenSubKey( "Software" ).OpenSubKey( "Microsoft" ).OpenSubKey( "Office" ).OpenSubKey( strVersion ).OpenSubKey( "Excel" ).OpenSubKey( "InstallRoot" );
    832.                 if( installKey == null )
    833.                 {
    834.                     return false;
    835.                 }
    836.                 return true;
    837.             }
    838.             catch
    839.             {
    840.                 return false;
    841.             }
    842.         }
    843.         #endregion
    844.  
    845.         #region 判断系统是否装word
    846.         /**//// <summary>
    847.         /// 判断系统是否装word
    848.         /// </summary>
    849.         /// <returns></returns>
    850.         public static bool IsInstallWord()
    851.         {
    852.             RegistryKey machineKey = Registry.LocalMachine;
    853.             if( IsInstallExcelByVersion( "12.0", machineKey ) )
    854.             {
    855.                 return true;
    856.             }
    857.             if( IsInstallExcelByVersion( "11.0", machineKey ) )
    858.             {
    859.                 return true;
    860.             }
    861.             return false;
    862.         }
    863.         /**//// <summary>
    864.         /// 判断系统是否装某版本的word
    865.         /// </summary>
    866.         /// <param name="strVersion">版本号</param>
    867.         /// <param name="machineKey"></param>
    868.         /// <returns></returns>
    869.         private static bool IsInstallWordByVersion( string strVersion, RegistryKey machineKey )
    870.         {
    871.             try
    872.             {
    873.                 RegistryKey installKey = machineKey.OpenSubKey( "Software" ).OpenSubKey( "Microsoft" ).OpenSubKey( "Office" ).OpenSubKey( strVersion ).OpenSubKey( "Word" ).OpenSubKey( "InstallRoot" );
    874.                 if( installKey == null )
    875.                 {
    876.                     return false;
    877.                 }
    878.                 return true;
    879.             }
    880.             catch
    881.             {
    882.                 return false;
    883.             }
    884.         }
    885.         #endregion              
    886.     }
    887. }

============ 欢迎各位老板打赏~ ===========

本文版权归Bruce's Blog所有,转载引用请完整注明以下信息:
本文作者:Bruce
本文地址:C#操作Word类库 | Bruce's Blog

C#操作Word类库:目前有1 条留言

  1. 商明航 : 2016年03月09日下午 4:28 回复

    不错的,挺齐全的

发表评论

留言无头像?