轉帖|使用教程|編輯:龔雪|2014-11-03 10:07:24.000|閱讀 10582 次
概述:利用Aspose.Words 完美生成word試卷(附示例代碼)
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
關聯產品:Aspose.Words
最近做了一個在線組卷的項目。主要功能實現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完全消除了以上問題,推薦給大家分享。
文件格式轉換工具75折限時促銷點擊查看>>>>
下面我把aspose.words組件的一些操作代碼分享給大家希望對需要的人有所幫助:
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; } } } }
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:慧都控件網