aspose.words 操作word生成试卷

最近做了一个在线组卷的项目。主要功能实现word排版、预览,生成试卷。刚开始涉及到word操作一心想到的就是 office COM组件 来操作word 。大概两周时间就写好整个系统的代码。然后就开始反复测试,本地感觉良好,能够顺利生成一份word试卷,并且性能还行。于是迫不及待的发布到了服务器。

 下面说说发布遇到的一些情况,首先一个就是遇到索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件失败,原因是出现以下错误: 8000401a 因为配置标识不正确,系统无法开始服务器进程。请检查用户名和密码。 (异常来自 HRESULT:0x8000401A)。 

首先这中问题全都是权限所导致,解决的办法只要配置权限就可以了。不光对excel和word有用,对所有的office产品都有效果。

进入正题,首先,在运行中输入dcomcnfg打开组件服务管理器->组件服务->我的电脑->DCOM->找到对应的Microsoft excel applicotion/Microsoft word 97-2003文档,然后右键属性激活启动权限都给足够了就ok了。 --------没问题这个问题解决了。

 

 下面再说说第二个情况》性能问题:由于我们该系统是我们网站下一个子系统。所以有一定的用户基础。该系统一上线就有大量的用户访问。刚开始一天组卷四五百份,慢慢的组卷量越来越大,这是系统就开始出问题了。首先一个就是在进程里面出现了很多 winWord.exe进程。不能结束掉。虽然系统代码里面Quit进程,并且对资源也进行了回收,但是问题始终得不到解决。大量winword.exe进程的后果就是服务器变慢了。应为该组件办本身就特别耗内存。

没办法问题要解决呀。最后的无赖之举就是KIll 写了一个定时服务,定时Kill掉没有运行的winword进程。这样做治标不治本的。、

 

这里要说一下微软Office是主要针对普通用户开发的桌面办公应用软件,它具有丰富的UI(用户界面)元素,是一套纯粹的本地运行软件或者说是客户端软件。Word自动化接口主要是为了方便窗口应用程序调用而设计的。例如Delphi、VB、C# Winform等开发的本地应用程序。虽然可以强制Visible为false,Word可以运行在服务器端代码里,但毕竟还是会带来许多棘手问题。

1. ASP.NET是基于B/S架构的。B/S架构下用户访问都是并发的,也就是说经常会出现同时N个用户对一个服务器页面发出请求。在这种情况下Word自动化调用会时常出现死进程。

2. 由于隐藏界面运行,一些涉及界面的可以在窗口程序里成功调用的接口,在服务器端调用就会失败,甚至崩溃,这种情况也会经常导致死进程。

3. 由于Word是复杂的桌面程序,并不符合一般Web服务程序简洁高效的标准,所以在服务器端运行时速度慢,并且还会消耗大量资源(CPU、内存),尤其不能支持大量用户同时访问,资源会很快耗尽。

4. 绝大部分开发者对COM技术比较陌生,在编程调用Word接口时经常存在一些代码错误,而又很难检查到问题所在,这又是导致死进程的经常因素。Word死进程不仅会消耗服务器资源,还经常会导致服务器页面不能创建新的Word自动化对象而无法继续工作。有网友提出死进程解决方法:编程Kill掉Word死进程,这样是治标不治本的做法,Word死进程是不在了,可是Word非正常关闭会导致很多资源无法及时释放。这样的Web服务器能持续工作多久恐怕就很难说了。

 

为了解决这些问题,笔者经过全面研究比较,发现网上有一款组件件aspose.words,完全消除了以上问题,推荐给大家分享。

 

下面我把aspose.words组件的一些操作代码分享给大家希望对需要的人有所帮助

  1.  private DocumentBuilder oWordApplic; //   a   reference   to   Word   application    
  2.         private Aspose.Words.Document oDoc; //   a   reference   to   the   document    
  3.         public void OpenWithTemplate(string strFileName)  
  4.         {  
  5.             if (!string.IsNullOrEmpty(strFileName))  
  6.             {  
  7.                 oDoc = new Aspose.Words.Document(strFileName);  
  8.             }  
  9.         }  
  10.   
  11.         public void Open()  
  12.         {  
  13.             oDoc = new Aspose.Words.Document();  
  14.         }  
  15.   
  16.         public void Builder()  
  17.         {  
  18.             oWordApplic = new DocumentBuilder(oDoc);  
  19.               
  20.               
  21.         }  
  22.         /// <summary>   
  23.         /// 保存文件   
  24.         /// </summary>   
  25.         /// <param name="strFileName"></param>   
  26.         public void SaveAs(string strFileName)  
  27.         {  
  28.   
  29.             if (this.Docversion == 2007)  
  30.             {  
  31.                 oDoc.Save(strFileName,SaveFormat.Docx);   
  32.             }else  
  33.             {  
  34.                 oDoc.Save(strFileName,SaveFormat.Doc);   
  35.             }  
  36.              
  37.         }  
  38.   
  39.         /// <summary>   
  40.         /// 添加内容   
  41.         /// </summary>   
  42.         /// <param name="strText"></param>   
  43.         public void InsertText(string strText, double conSize, bool conBold, string conAlign)  
  44.         {  
  45.             oWordApplic.Bold = conBold;  
  46.             oWordApplic.Font.Size = conSize;  
  47.             switch (conAlign)  
  48.             {  
  49.                 case "left":  
  50.                     oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Left;  
  51.                     break;  
  52.                 case "center":  
  53.                     oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;  
  54.                     break;  
  55.                 case "right":  
  56.                     oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Right;  
  57.                     break;  
  58.                 default:  
  59.                     oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Left;  
  60.                     break;  
  61.             }  
  62.             oWordApplic.Writeln(strText);  
  63.                
  64.         }  
  65.   
  66.         /// <summary>   
  67.         /// 添加内容   
  68.         /// </summary>   
  69.         /// <param name="strText"></param>   
  70.         public void WriteText(string strText, double conSize, bool conBold, string conAlign)  
  71.         {  
  72.             oWordApplic.Bold = conBold;  
  73.             oWordApplic.Font.Size = conSize;  
  74.             switch (conAlign)  
  75.             {  
  76.                 case "left":  
  77.                     oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Left;  
  78.                     break;  
  79.                 case "center":  
  80.                     oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;  
  81.                     break;  
  82.                 case "right":  
  83.                     oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Right;  
  84.                     break;  
  85.                 default:  
  86.                     oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Left;  
  87.                     break;  
  88.             }  
  89.             oWordApplic.Write(strText);  
  90.   
  91.         }  
  92.  
  93.  
  94.         #region 设置纸张   
  95.         public void setPaperSize(string papersize)  
  96.         {  
  97.   
  98.             switch (papersize)  
  99.             {  
  100.                 case "A4":  
  101.                     foreach (Aspose.Words.Section section in oDoc)  
  102.                     {  
  103.                         section.PageSetup.PaperSize = PaperSize.A4;  
  104.                         section.PageSetup.Orientation = Orientation.Portrait;  
  105.                         section.PageSetup.VerticalAlignment = Aspose.Words.PageVerticalAlignment.Top;  
  106.                     }  
  107.                     break;  
  108.                 case "A4H"://A4横向   
  109.                     foreach (Aspose.Words.Section section in oDoc)  
  110.                     {  
  111.                         section.PageSetup.PaperSize = PaperSize.A4;  
  112.                         section.PageSetup.Orientation = Orientation.Landscape;  
  113.                         section.PageSetup.TextColumns.SetCount(2);  
  114.                         section.PageSetup.TextColumns.EvenlySpaced = true;  
  115.                         section.PageSetup.TextColumns.LineBetween =true;  
  116.                         //section.PageSetup.LeftMargin = double.Parse("3.35");   
  117.                         //section.PageSetup.RightMargin =double.Parse("0.99");   
  118.                     }  
  119.                     break;  
  120.                 case "A3":  
  121.                     foreach (Aspose.Words.Section section in oDoc)  
  122.                     {  
  123.                         section.PageSetup.PaperSize = PaperSize.A3;  
  124.                         section.PageSetup.Orientation = Orientation.Portrait;  
  125.                          
  126.                     }  
  127.                      
  128.                     break;  
  129.                 case "A3H"://A3横向   
  130.   
  131.                     foreach (Aspose.Words.Section section in oDoc)  
  132.                     {  
  133.                         section.PageSetup.PaperSize = PaperSize.A3;  
  134.                         section.PageSetup.Orientation = Orientation.Landscape;  
  135.                         section.PageSetup.TextColumns.SetCount(2);  
  136.                         section.PageSetup.TextColumns.EvenlySpaced = true;  
  137.                         section.PageSetup.TextColumns.LineBetween = true;  
  138.   
  139.                     }  
  140.   
  141.                     break;  
  142.   
  143.                 case "16K":  
  144.   
  145.                     foreach (Aspose.Words.Section section in oDoc)  
  146.                     {  
  147.                         section.PageSetup.PaperSize = PaperSize.B5;  
  148.                         section.PageSetup.Orientation = Orientation.Portrait;  
  149.   
  150.                     }  
  151.                      
  152.                     break;  
  153.   
  154.                 case "8KH":  
  155.   
  156.                     foreach (Aspose.Words.Section section in oDoc)  
  157.                     {  
  158.   
  159.                         section.PageSetup.PageWidth = double.Parse("36.4 ");//纸张宽度   
  160.                         section.PageSetup.PageHeight = double.Parse("25.7");//纸张高度   
  161.                         section.PageSetup.Orientation = Orientation.Landscape;  
  162.                         section.PageSetup.TextColumns.SetCount(2);  
  163.                         section.PageSetup.TextColumns.EvenlySpaced = true;  
  164.                         section.PageSetup.TextColumns.LineBetween = true;  
  165.                         //section.PageSetup.LeftMargin = double.Parse("3.35");   
  166.                         //section.PageSetup.RightMargin = double.Parse("0.99");   
  167.                     }  
  168.   
  169.                    
  170.   
  171.                     break;  
  172.             }  
  173.         }  
  174.         #endregion   
  175.   
  176.         public void SetHeade(string strBookmarkName, string text)  
  177.         {  
  178.             if (oDoc.Range.Bookmarks[strBookmarkName] != null)  
  179.             {  
  180.                 Aspose.Words.Bookmark mark = oDoc.Range.Bookmarks[strBookmarkName];  
  181.                 mark.Text = text;  
  182.             }  
  183.         }  
  184.         public void InsertFile(string vfilename)  
  185.         {  
  186.             Aspose.Words.Document srcDoc = new Aspose.Words.Document(vfilename);  
  187.                       Node insertAfterNode = oWordApplic.CurrentParagraph.PreviousSibling;  
  188.                       InsertDocument(insertAfterNode, oDoc, srcDoc);  
  189.              
  190.         }  
  191.   
  192.         public void InsertFile(string vfilename, string strBookmarkName,int pNum)  
  193.         {  
  194.             //Aspose.Words.Document srcDoc = new Aspose.Words.Document(vfilename);   
  195.             //Aspose.Words.Bookmark bookmark = oDoc.Range.Bookmarks[strBookmarkName];   
  196.             //InsertDocument(bookmark.BookmarkStart.ParentNode, srcDoc);   
  197.             //替换插入word内容   
  198.             oWordApplic.Document.Range.Replace(new System.Text.RegularExpressions.Regex(strBookmarkName),  
  199.                 new InsertDocumentAtReplaceHandler(vfilename, pNum), false);  
  200.              
  201.   
  202.         }  
  203.         /// <summary>   
  204.         /// 插入word内容   
  205.         /// </summary>   
  206.         /// <param name="insertAfterNode"></param>   
  207.         /// <param name="mainDoc"></param>   
  208.         /// <param name="srcDoc"></param>   
  209.         public static void InsertDocument(Node insertAfterNode, Aspose.Words.Document mainDoc, Aspose.Words.Document srcDoc)  
  210.         {  
  211.             // Make sure that the node is either a pargraph or table.   
  212.             if ((insertAfterNode.NodeType != NodeType.Paragraph)  
  213.                 & (insertAfterNode.NodeType != NodeType.Table))  
  214.                 throw new Exception("The destination node should be either a paragraph or table.");  
  215.   
  216.             //We will be inserting into the parent of the destination paragraph.   
  217.   
  218.             CompositeNode dstStory = insertAfterNode.ParentNode;  
  219.   
  220.             //Remove empty paragraphs from the end of document   
  221.   
  222.             while (null != srcDoc.LastSection.Body.LastParagraph && !srcDoc.LastSection.Body.LastParagraph.HasChildNodes)  
  223.             {  
  224.                 srcDoc.LastSection.Body.LastParagraph.Remove();  
  225.             }  
  226.             NodeImporter importer = new NodeImporter(srcDoc, mainDoc, ImportFormatMode.KeepSourceFormatting);  
  227.   
  228.             //Loop through all sections in the source document.   
  229.   
  230.             int sectCount = srcDoc.Sections.Count;  
  231.   
  232.             for (int sectIndex = 0; sectIndex < sectCount; sectIndex++)  
  233.             {  
  234.                 Aspose.Words.Section srcSection = srcDoc.Sections[sectIndex];  
  235.                 //Loop through all block level nodes (paragraphs and tables) in the body of the section.   
  236.                 int nodeCount = srcSection.Body.ChildNodes.Count;  
  237.                 for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++)  
  238.                 {  
  239.                     Node srcNode = srcSection.Body.ChildNodes[nodeIndex];  
  240.                     Node newNode = importer.ImportNode(srcNode, true);  
  241.                     dstStory.InsertAfter(newNode, insertAfterNode);  
  242.                     insertAfterNode = newNode;  
  243.                 }  
  244.             }  
  245.   
  246.   
  247.         }  
  248.   
  249.         static void InsertDocument(Node insertAfterNode, Aspose.Words.Document srcDoc)  
  250.         {  
  251.             // Make sure that the node is either a paragraph or table.   
  252.             if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &  
  253.               (!insertAfterNode.NodeType.Equals(NodeType.Table)))  
  254.                 throw new ArgumentException("The destination node should be either a paragraph or table.");  
  255.   
  256.             // We will be inserting into the parent of the destination paragraph.   
  257.             CompositeNode dstStory = insertAfterNode.ParentNode;  
  258.   
  259.             // This object will be translating styles and lists during the import.   
  260.             NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting);  
  261.   
  262.             // Loop through all sections in the source document.   
  263.             foreach (Aspose.Words.Section srcSection in srcDoc.Sections)  
  264.             {  
  265.                 // Loop through all block level nodes (paragraphs and tables) in the body of the section.   
  266.                 foreach (Node srcNode in srcSection.Body)  
  267.                 {  
  268.                     // Let's skip the node if it is a last empty paragraph in a section.   
  269.                     if (srcNode.NodeType.Equals(NodeType.Paragraph))  
  270.                     {  
  271.                         Aspose.Words.Paragraph para = (Aspose.Words.Paragraph)srcNode;  
  272.                         if (para.IsEndOfSection && !para.HasChildNodes)  
  273.                             continue;  
  274.                     }  
  275.   
  276.                     // This creates a clone of the node, suitable for insertion into the destination document.   
  277.                     Node newNode = importer.ImportNode(srcNode, true);  
  278.   
  279.                     // Insert new node after the reference node.   
  280.                     dstStory.InsertAfter(newNode, insertAfterNode);  
  281.                     insertAfterNode = newNode;  
  282.                 }  
  283.             }  
  284.         }  
  285.         /// <summary>   
  286.         /// 换行   
  287.         /// </summary>   
  288.         public void InsertLineBreak()  
  289.         {  
  290.             oWordApplic.InsertBreak(BreakType.LineBreak);  
  291.         }  
  292.         /// <summary>   
  293.         /// 换多行   
  294.         /// </summary>   
  295.         /// <param name="nline"></param>   
  296.         public void InsertLineBreak(int nline)  
  297.         {  
  298.             for (int i = 0; i < nline; i++)  
  299.                 oWordApplic.InsertBreak(BreakType.LineBreak);  
  300.         }  
  301.  
  302.         #region InsertScoreTable   
  303.         public bool InsertScoreTable(bool dishand, bool distab, string handText)  
  304.         {  
  305.             try  
  306.             {  
  307.   
  308.               
  309.                 oWordApplic.StartTable();//开始画Table   
  310.                 oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Left;  
  311.                 //添加Word表格   
  312.                 oWordApplic.InsertCell();  
  313.                 oWordApplic.CellFormat.Width = 115.0;  
  314.                 oWordApplic.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(115);  
  315.                 oWordApplic.CellFormat.Borders.LineStyle = LineStyle.None;  
  316.                  
  317.                 oWordApplic.StartTable();//开始画Table   
  318.                 oWordApplic.RowFormat.Height = 20.2;  
  319.                 oWordApplic.InsertCell();  
  320.                 oWordApplic.CellFormat.Borders.LineStyle = LineStyle.Single;  
  321.                 oWordApplic.Font.Size = 10.5;  
  322.                 oWordApplic.Bold = false;  
  323.                 oWordApplic.Write("评卷人");  
  324.   
  325.                 oWordApplic.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐   
  326.                 oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;  
  327.                 oWordApplic.CellFormat.Width = 50.0;  
  328.                 oWordApplic.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(50);  
  329.                 oWordApplic.RowFormat.Height = 20.0;  
  330.                 oWordApplic.InsertCell();  
  331.                 oWordApplic.CellFormat.Borders.LineStyle = LineStyle.Single;  
  332.                 oWordApplic.Font.Size = 10.5;  
  333.                 oWordApplic.Bold = false;  
  334.                 oWordApplic.Write("得分");  
  335.                 oWordApplic.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐   
  336.                 oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;  
  337.                 oWordApplic.CellFormat.Width = 50.0;  
  338.                 oWordApplic.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(50);  
  339.                 oWordApplic.EndRow();  
  340.                 oWordApplic.RowFormat.Height = 25.0;  
  341.                 oWordApplic.InsertCell();  
  342.                 oWordApplic.RowFormat.Height = 25.0;  
  343.                 oWordApplic.InsertCell();  
  344.                 oWordApplic.EndRow();  
  345.                 oWordApplic.EndTable();  
  346.   
  347.                 oWordApplic.InsertCell();  
  348.                 oWordApplic.CellFormat.Width = 300.0;  
  349.                 oWordApplic.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.Auto;  
  350.                 oWordApplic.CellFormat.Borders.LineStyle = LineStyle.None;  
  351.   
  352.                  
  353.                 oWordApplic.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐   
  354.                 oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Left;  
  355.                 oWordApplic.Font.Size = 11;  
  356.                 oWordApplic.Bold = true;  
  357.                 oWordApplic.Write(handText);  
  358.                 oWordApplic.EndRow();  
  359.                 oWordApplic.RowFormat.Height = 28;  
  360.                 oWordApplic.EndTable();  
  361.                 return true;  
  362.             }  
  363.             catch  
  364.             {  
  365.   
  366.                 return false;  
  367.             }  
  368.   
  369.         }  
  370.         #endregion  
  371.          #region 插入表格   
  372.         public bool InsertTable(System.Data.DataTable dt, bool haveBorder)  
  373.         {  
  374.             Aspose.Words.Tables.Table  table= oWordApplic.StartTable();//开始画Table   
  375.             ParagraphAlignment paragraphAlignmentValue = oWordApplic.ParagraphFormat.Alignment;  
  376.             oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;  
  377.             //添加Word表格   
  378.             for (int row = 0; row < dt.Rows.Count; row++)  
  379.             {  
  380.                  oWordApplic.RowFormat.Height =25;  
  381.                 for (int col = 0; col < dt.Columns.Count; col++)  
  382.                 {  
  383.                     oWordApplic.InsertCell();  
  384.                     oWordApplic.Font.Size = 10.5;  
  385.                     oWordApplic.Font.Name = "宋体";  
  386.                     oWordApplic.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐   
  387.                     oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐   
  388.                     oWordApplic.CellFormat.Width = 50.0;  
  389.                     oWordApplic.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(50);  
  390.                     if (haveBorder == true)  
  391.                     {  
  392.                         //设置外框样式      
  393.                         oWordApplic.CellFormat.Borders.LineStyle = LineStyle.Single;  
  394.                         //样式设置结束      
  395.                     }  
  396.   
  397.                     oWordApplic.Write(dt.Rows[row][col].ToString());  
  398.                 }  
  399.   
  400.                 oWordApplic.EndRow();  
  401.   
  402.             }  
  403.             oWordApplic.EndTable();  
  404.             oWordApplic.ParagraphFormat.Alignment = paragraphAlignmentValue;  
  405.             table.Alignment=Aspose.Words.Tables.TableAlignment.Center;  
  406.             table.PreferredWidth = Aspose.Words.Tables.PreferredWidth.Auto;  
  407.             
  408.   
  409.   
  410.             return true;  
  411.         }  
  412.         #endregion   
  413.   
  414.   
  415.         public void InsertPagebreak( )  
  416.         {  
  417.             oWordApplic.InsertBreak(BreakType.PageBreak);  
  418.               
  419.         }  
  420.         public void InsertBookMark(string BookMark)  
  421.         {  
  422.             oWordApplic.StartBookmark(BookMark);  
  423.             oWordApplic.EndBookmark(BookMark);  
  424.   
  425.         }  
  426.         public void GotoBookMark(string strBookMarkName)  
  427.         {  
  428.             oWordApplic.MoveToBookmark(strBookMarkName);  
  429.         }  
  430.         public void ClearBookMark()  
  431.         {  
  432.             oDoc.Range.Bookmarks.Clear();  
  433.         }  
  434.   
  435.         public void ReplaceText(string oleText, string newText)  
  436.         {  
  437.             //System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(oleText);   
  438.             oDoc.Range.Replace(oleText, newText, false,false);  
  439.   
  440.         }  
  441.         private class InsertDocumentAtReplaceHandler : IReplacingCallback  
  442.         {  
  443.             private string vfilename;  
  444.             private int pNum;  
  445.   
  446.             public InsertDocumentAtReplaceHandler(string filename, int _pNum)  
  447.             {  
  448.                 this.vfilename = filename;  
  449.                 this.pNum = _pNum;  
  450.             }  
  451.             ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)  
  452.             {  
  453.                 Document subDoc = new Document(this.vfilename);  
  454.                 subDoc.FirstSection.Body.FirstParagraph.InsertAfter(new Run(subDoc, this.pNum + "."), null);  
  455.                   
  456.                 // Insert a document after the paragraph, containing the match text.   
  457.                 Node currentNode = e.MatchNode;  
  458.                 Paragraph para = (Paragraph)e.MatchNode.ParentNode;  
  459.                 InsertDocument(para, subDoc);  
  460.                 // Remove the paragraph with the match text.   
  461.                 e.MatchNode.Remove();  
  462.                 e.MatchNode.Range.Delete();  
  463.   
  464.   
  465.   
  466.                 return ReplaceAction.Skip;  
  467.             }  
  468.         }  
  469.     }  
  470. }  
 private DocumentBuilder oWordApplic; //   a   reference   to   Word   application 
        private Aspose.Words.Document oDoc; //   a   reference   to   the   document 
        public void OpenWithTemplate(string strFileName)
        {
            if (!string.IsNullOrEmpty(strFileName))
            {
                oDoc = new Aspose.Words.Document(strFileName);
            }
        }

        public void Open()
        {
            oDoc = new Aspose.Words.Document();
        }

        public void Builder()
        {
            oWordApplic = new DocumentBuilder(oDoc);
            
            
        }
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="strFileName"></param>
        public void SaveAs(string strFileName)
        {

            if (this.Docversion == 2007)
            {
                oDoc.Save(strFileName,SaveFormat.Docx); 
            }else
            {
                oDoc.Save(strFileName,SaveFormat.Doc); 
            }
           
        }

        /// <summary>
        /// 添加内容
        /// </summary>
        /// <param name="strText"></param>
        public void InsertText(string strText, double conSize, bool conBold, string conAlign)
        {
            oWordApplic.Bold = conBold;
            oWordApplic.Font.Size = conSize;
            switch (conAlign)
            {
                case "left":
                    oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Left;
                    break;
                case "center":
                    oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                    break;
                case "right":
                    oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Right;
                    break;
                default:
                    oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Left;
                    break;
            }
            oWordApplic.Writeln(strText);
             
        }

        /// <summary>
        /// 添加内容
        /// </summary>
        /// <param name="strText"></param>
        public void WriteText(string strText, double conSize, bool conBold, string conAlign)
        {
            oWordApplic.Bold = conBold;
            oWordApplic.Font.Size = conSize;
            switch (conAlign)
            {
                case "left":
                    oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Left;
                    break;
                case "center":
                    oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                    break;
                case "right":
                    oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Right;
                    break;
                default:
                    oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Left;
                    break;
            }
            oWordApplic.Write(strText);

        }


        #region 设置纸张
        public void setPaperSize(string papersize)
        {

            switch (papersize)
            {
                case "A4":
                    foreach (Aspose.Words.Section section in oDoc)
                    {
                        section.PageSetup.PaperSize = PaperSize.A4;
                        section.PageSetup.Orientation = Orientation.Portrait;
                        section.PageSetup.VerticalAlignment = Aspose.Words.PageVerticalAlignment.Top;
                    }
                    break;
                case "A4H"://A4横向
                    foreach (Aspose.Words.Section section in oDoc)
                    {
                        section.PageSetup.PaperSize = PaperSize.A4;
                        section.PageSetup.Orientation = Orientation.Landscape;
                        section.PageSetup.TextColumns.SetCount(2);
                        section.PageSetup.TextColumns.EvenlySpaced = true;
                        section.PageSetup.TextColumns.LineBetween =true;
                        //section.PageSetup.LeftMargin = double.Parse("3.35");
                        //section.PageSetup.RightMargin =double.Parse("0.99");
                    }
                    break;
                case "A3":
                    foreach (Aspose.Words.Section section in oDoc)
                    {
                        section.PageSetup.PaperSize = PaperSize.A3;
                        section.PageSetup.Orientation = Orientation.Portrait;
                       
                    }
                   
                    break;
                case "A3H"://A3横向

                    foreach (Aspose.Words.Section section in oDoc)
                    {
                        section.PageSetup.PaperSize = PaperSize.A3;
                        section.PageSetup.Orientation = Orientation.Landscape;
                        section.PageSetup.TextColumns.SetCount(2);
                        section.PageSetup.TextColumns.EvenlySpaced = true;
                        section.PageSetup.TextColumns.LineBetween = true;

                    }

                    break;

                case "16K":

                    foreach (Aspose.Words.Section section in oDoc)
                    {
                        section.PageSetup.PaperSize = PaperSize.B5;
                        section.PageSetup.Orientation = Orientation.Portrait;

                    }
                   
                    break;

                case "8KH":

                    foreach (Aspose.Words.Section section in oDoc)
                    {

                        section.PageSetup.PageWidth = double.Parse("36.4 ");//纸张宽度
                        section.PageSetup.PageHeight = double.Parse("25.7");//纸张高度
                        section.PageSetup.Orientation = Orientation.Landscape;
                        section.PageSetup.TextColumns.SetCount(2);
                        section.PageSetup.TextColumns.EvenlySpaced = true;
                        section.PageSetup.TextColumns.LineBetween = true;
                        //section.PageSetup.LeftMargin = double.Parse("3.35");
                        //section.PageSetup.RightMargin = double.Parse("0.99");
                    }

                 

                    break;
            }
        }
        #endregion

        public void SetHeade(string strBookmarkName, string text)
        {
            if (oDoc.Range.Bookmarks[strBookmarkName] != null)
            {
                Aspose.Words.Bookmark mark = oDoc.Range.Bookmarks[strBookmarkName];
                mark.Text = text;
            }
        }
        public void InsertFile(string vfilename)
        {
            Aspose.Words.Document srcDoc = new Aspose.Words.Document(vfilename);
                      Node insertAfterNode = oWordApplic.CurrentParagraph.PreviousSibling;
                      InsertDocument(insertAfterNode, oDoc, srcDoc);
           
        }

        public void InsertFile(string vfilename, string strBookmarkName,int pNum)
        {
            //Aspose.Words.Document srcDoc = new Aspose.Words.Document(vfilename);
            //Aspose.Words.Bookmark bookmark = oDoc.Range.Bookmarks[strBookmarkName];
            //InsertDocument(bookmark.BookmarkStart.ParentNode, srcDoc);
            //替换插入word内容
            oWordApplic.Document.Range.Replace(new System.Text.RegularExpressions.Regex(strBookmarkName),
                new InsertDocumentAtReplaceHandler(vfilename, pNum), false);
           

        }
        /// <summary>
        /// 插入word内容
        /// </summary>
        /// <param name="insertAfterNode"></param>
        /// <param name="mainDoc"></param>
        /// <param name="srcDoc"></param>
        public static void InsertDocument(Node insertAfterNode, Aspose.Words.Document mainDoc, Aspose.Words.Document srcDoc)
        {
            // Make sure that the node is either a pargraph or table.
            if ((insertAfterNode.NodeType != NodeType.Paragraph)
                & (insertAfterNode.NodeType != NodeType.Table))
                throw new Exception("The destination node should be either a paragraph or table.");

            //We will be inserting into the parent of the destination paragraph.

            CompositeNode dstStory = insertAfterNode.ParentNode;

            //Remove empty paragraphs from the end of document

            while (null != srcDoc.LastSection.Body.LastParagraph && !srcDoc.LastSection.Body.LastParagraph.HasChildNodes)
            {
                srcDoc.LastSection.Body.LastParagraph.Remove();
            }
            NodeImporter importer = new NodeImporter(srcDoc, mainDoc, ImportFormatMode.KeepSourceFormatting);

            //Loop through all sections in the source document.

            int sectCount = srcDoc.Sections.Count;

            for (int sectIndex = 0; sectIndex < sectCount; sectIndex++)
            {
                Aspose.Words.Section srcSection = srcDoc.Sections[sectIndex];
                //Loop through all block level nodes (paragraphs and tables) in the body of the section.
                int nodeCount = srcSection.Body.ChildNodes.Count;
                for (int nodeIndex = 0; nodeIndex < nodeCount; nodeIndex++)
                {
                    Node srcNode = srcSection.Body.ChildNodes[nodeIndex];
                    Node newNode = importer.ImportNode(srcNode, true);
                    dstStory.InsertAfter(newNode, insertAfterNode);
                    insertAfterNode = newNode;
                }
            }


        }

        static void InsertDocument(Node insertAfterNode, Aspose.Words.Document srcDoc)
        {
            // Make sure that the node is either a paragraph or table.
            if ((!insertAfterNode.NodeType.Equals(NodeType.Paragraph)) &
              (!insertAfterNode.NodeType.Equals(NodeType.Table)))
                throw new ArgumentException("The destination node should be either a paragraph or table.");

            // We will be inserting into the parent of the destination paragraph.
            CompositeNode dstStory = insertAfterNode.ParentNode;

            // This object will be translating styles and lists during the import.
            NodeImporter importer = new NodeImporter(srcDoc, insertAfterNode.Document, ImportFormatMode.KeepSourceFormatting);

            // Loop through all sections in the source document.
            foreach (Aspose.Words.Section srcSection in srcDoc.Sections)
            {
                // Loop through all block level nodes (paragraphs and tables) in the body of the section.
                foreach (Node srcNode in srcSection.Body)
                {
                    // Let's skip the node if it is a last empty paragraph in a section.
                    if (srcNode.NodeType.Equals(NodeType.Paragraph))
                    {
                        Aspose.Words.Paragraph para = (Aspose.Words.Paragraph)srcNode;
                        if (para.IsEndOfSection && !para.HasChildNodes)
                            continue;
                    }

                    // This creates a clone of the node, suitable for insertion into the destination document.
                    Node newNode = importer.ImportNode(srcNode, true);

                    // Insert new node after the reference node.
                    dstStory.InsertAfter(newNode, insertAfterNode);
                    insertAfterNode = newNode;
                }
            }
        }
        /// <summary>
        /// 换行
        /// </summary>
        public void InsertLineBreak()
        {
            oWordApplic.InsertBreak(BreakType.LineBreak);
        }
        /// <summary>
        /// 换多行
        /// </summary>
        /// <param name="nline"></param>
        public void InsertLineBreak(int nline)
        {
            for (int i = 0; i < nline; i++)
                oWordApplic.InsertBreak(BreakType.LineBreak);
        }

        #region InsertScoreTable
        public bool InsertScoreTable(bool dishand, bool distab, string handText)
        {
            try
            {

            
                oWordApplic.StartTable();//开始画Table
                oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Left;
                //添加Word表格
                oWordApplic.InsertCell();
                oWordApplic.CellFormat.Width = 115.0;
                oWordApplic.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(115);
                oWordApplic.CellFormat.Borders.LineStyle = LineStyle.None;
               
                oWordApplic.StartTable();//开始画Table
                oWordApplic.RowFormat.Height = 20.2;
                oWordApplic.InsertCell();
                oWordApplic.CellFormat.Borders.LineStyle = LineStyle.Single;
                oWordApplic.Font.Size = 10.5;
                oWordApplic.Bold = false;
                oWordApplic.Write("评卷人");

                oWordApplic.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                oWordApplic.CellFormat.Width = 50.0;
                oWordApplic.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(50);
                oWordApplic.RowFormat.Height = 20.0;
                oWordApplic.InsertCell();
                oWordApplic.CellFormat.Borders.LineStyle = LineStyle.Single;
                oWordApplic.Font.Size = 10.5;
                oWordApplic.Bold = false;
                oWordApplic.Write("得分");
                oWordApplic.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                oWordApplic.CellFormat.Width = 50.0;
                oWordApplic.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(50);
                oWordApplic.EndRow();
                oWordApplic.RowFormat.Height = 25.0;
                oWordApplic.InsertCell();
                oWordApplic.RowFormat.Height = 25.0;
                oWordApplic.InsertCell();
                oWordApplic.EndRow();
                oWordApplic.EndTable();

                oWordApplic.InsertCell();
                oWordApplic.CellFormat.Width = 300.0;
                oWordApplic.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.Auto;
                oWordApplic.CellFormat.Borders.LineStyle = LineStyle.None;

               
                oWordApplic.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Left;
                oWordApplic.Font.Size = 11;
                oWordApplic.Bold = true;
                oWordApplic.Write(handText);
                oWordApplic.EndRow();
                oWordApplic.RowFormat.Height = 28;
                oWordApplic.EndTable();
                return true;
            }
            catch
            {

                return false;
            }

        }
        #endregion
         #region 插入表格
        public bool InsertTable(System.Data.DataTable dt, bool haveBorder)
        {
            Aspose.Words.Tables.Table  table= oWordApplic.StartTable();//开始画Table
            ParagraphAlignment paragraphAlignmentValue = oWordApplic.ParagraphFormat.Alignment;
            oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            //添加Word表格
            for (int row = 0; row < dt.Rows.Count; row++)
            {
                 oWordApplic.RowFormat.Height =25;
                for (int col = 0; col < dt.Columns.Count; col++)
                {
                    oWordApplic.InsertCell();
                    oWordApplic.Font.Size = 10.5;
                    oWordApplic.Font.Name = "宋体";
                    oWordApplic.CellFormat.VerticalAlignment = Aspose.Words.Tables.CellVerticalAlignment.Center;//垂直居中对齐
                    oWordApplic.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中对齐
                    oWordApplic.CellFormat.Width = 50.0;
                    oWordApplic.CellFormat.PreferredWidth = Aspose.Words.Tables.PreferredWidth.FromPoints(50);
                    if (haveBorder == true)
                    {
                        //设置外框样式   
                        oWordApplic.CellFormat.Borders.LineStyle = LineStyle.Single;
                        //样式设置结束   
                    }

                    oWordApplic.Write(dt.Rows[row][col].ToString());
                }

                oWordApplic.EndRow();

            }
            oWordApplic.EndTable();
            oWordApplic.ParagraphFormat.Alignment = paragraphAlignmentValue;
            table.Alignment=Aspose.Words.Tables.TableAlignment.Center;
            table.PreferredWidth = Aspose.Words.Tables.PreferredWidth.Auto;
          


            return true;
        }
        #endregion


        public void InsertPagebreak( )
        {
            oWordApplic.InsertBreak(BreakType.PageBreak);
            
        }
        public void InsertBookMark(string BookMark)
        {
            oWordApplic.StartBookmark(BookMark);
            oWordApplic.EndBookmark(BookMark);

        }
        public void GotoBookMark(string strBookMarkName)
        {
            oWordApplic.MoveToBookmark(strBookMarkName);
        }
        public void ClearBookMark()
        {
            oDoc.Range.Bookmarks.Clear();
        }

        public void ReplaceText(string oleText, string newText)
        {
            //System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(oleText);
            oDoc.Range.Replace(oleText, newText, false,false);

        }
        private class InsertDocumentAtReplaceHandler : IReplacingCallback
        {
            private string vfilename;
            private int pNum;

            public InsertDocumentAtReplaceHandler(string filename, int _pNum)
            {
                this.vfilename = filename;
                this.pNum = _pNum;
            }
            ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
            {
                Document subDoc = new Document(this.vfilename);
                subDoc.FirstSection.Body.FirstParagraph.InsertAfter(new Run(subDoc, this.pNum + "."), null);
                
                // Insert a document after the paragraph, containing the match text.
                Node currentNode = e.MatchNode;
                Paragraph para = (Paragraph)e.MatchNode.ParentNode;
                InsertDocument(para, subDoc);
                // Remove the paragraph with the match text.
                e.MatchNode.Remove();
                e.MatchNode.Range.Delete();



                return ReplaceAction.Skip;
            }
        }
    }
}

最后来看看生成的word试卷效果

 

附件地址:下载aspose.word操作源码

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值