一、前言
PageOffice是一款幫助Web應用系統或Web網站實現用戶在線編輯Word、Excel、PowerPoint文檔,Word/Excel模板動態填充,Word/Excel在線輸入提交,系統數據導入導出word、excel文檔的Office快速開發組件庫,是目前把Office應用到Web平台上的最全面、最先進的解決方案。PageOffice為軟件開發者構建了一套簡潔高效、統一的Office對象接口,同時無縫支持doc、docx、xls、xlsx、ppt、pptx等流行Office文件格式。
簡而言之就是可以在線編寫office文件的產品。
二、安裝PageOffice
專業版試用序列號: 2C697-4FC8-F274-3DD88
1. 雙擊運行Setup.exe安裝服務器組件。(可以到官網下載安裝程序)
2. 如果運行示例,用VS.Net打開MvcApplication4.sln即可運行。
3. 如果新建網站或集成PageOffice到您現有的網站里:
1). 雙擊運行Setup.exe安裝服務器組件;
2). 拷貝“集成文件”目錄下的“pageoffice”文件夾到您自己網站的根目錄下;
2). VS.NET工具箱拖放PageOffice控件,雙擊控件,在事件代碼中編寫代碼。
------我的項目是.net MVC4 直接把 “pageoffice”文件夾放到自己網站的根目錄下;
三、使用
使用就分為編輯一個指定路徑下的文件,並保存
1、在網中打開一個指定路徑下的word
我的文件的路徑是:D:\project\A27\A27_Source\Web\OfficeTemp\總結報告.docx
如何打開該路徑下的文件,直接上代碼吧
public ActionResult EditReport() { ViewBag.Message = "Your contact page."; System.Web.UI.Page page = new System.Web.UI.Page(); string controlOutput = string.Empty; PageOffice.PageOfficeCtrl pc = new PageOffice.PageOfficeCtrl(); try { string fileName = "總結報告.docx"; string filePath = Server.MapPath("~/OfficeTemp/")+fileName; string currfilepath = "/" + fileName; pc.SaveFilePage = Url.Content("SaveDoc") + "?path=" + Server.UrlEncode(currfilepath); if (filePath == null) throw new ApplicationException("配置文件中未找到對應系統的項"); pc.ServerPage = Url.Content("~/pageoffice/server.aspx"); pc.WebOpen(filePath, PageOffice.OpenModeType.docAdmin, "s"); result.IsSuccess = true; page.Controls.Add(pc); StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { Server.Execute(page, htw, false); controlOutput = sb.ToString(); } } ViewBag.EditorHtml = controlOutput; } catch (Exception err) { throw err; } return PartialView(); }
2、保存編輯后的word, 保存時調用的saveDoc方法和參數正是編輯時這段代碼提供的:
pc.SaveFilePage = Url.Content("SaveDoc") + "?path=" + Server.UrlEncode(currfilepath);
public ActionResult SaveDoc(string path) { string filePath = Server.MapPath("~/OfficeTemp/" + path); PageOffice.FileSaver fs = new PageOffice.FileSaver(); fs.SaveToFile(filePath); fs.Close(); return View(); }
四、根據數據庫動態生成word文件
生成word並不是pageoffice的功能,但是會一起與該組件一起使用
1、生成word
/// <summary> /// 報告word /// </summary> /// <param name="wellboreId"></param> /// <returns></returns> public string OutPutDoc(Guid wellboreId, string appendixTypes, string wellboreNo) { try { string filePathNew = Server.MapPath("~/OfficeTemp/") + wellbore_No + "/" + HttpContext.User.Identity.Name + "/";//Server.MapPath("~/Upload/LogReportTemp/") +"\\" + HttpContext.User.Identity.Name; //生成文件夾 Directory.CreateDirectory(filePathNew); string fullfileName = filePathNew + fileName; string mainDocPath = Server.MapPath("~/Upload/LogReportTemp/GeoSummaryReport_template.docx");//Server.MapPath("~/Upload/LogReportTemp/LS25-1-5測井作業總結報告01.docx using (var mainDoc =WordprocessingDocument.Open(mainDocPath, false)) using (var resultDoc = WordprocessingDocument.Create(fullfileName, WordprocessingDocumentType.Document)) { MainDocumentPart mainPart = resultDoc.MainDocumentPart; foreach (var part in mainDoc.Parts) { if (part.OpenXmlPart.ContentType != "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml") resultDoc.AddPart(part.OpenXmlPart, part.RelationshipId); else if (mainPart == null) { mainPart = (MainDocumentPart)resultDoc.AddPart(part.OpenXmlPart, part.RelationshipId); //通過替換OuterXml中的占位符替換文本 mainPart.Document.Body = new Body(GeoSummaryReportHelper.XmlStringReplace(wellboreId, wellbore_No, mainDoc.MainDocumentPart.Document.Body.OuterXml, appendixTypes)); var bookMarks = GeoSummaryReportHelper.FindBookmarks(resultDoc.MainDocumentPart.Document); //替換書簽中的內容 foreach (var end in bookMarks) { //為了滿足甲方格式要求,使用模板生成方式 if (end.Key == "SuizuanTypeMark") GeoSummaryReportHelper.CreateSuiZuanTable(end,resultDoc ,wellbore_No, "LWD",wellboreId); if (end.Key == "DianLanTypeMark") GeoSummaryReportHelper.CreateDianLanTable(end, resultDoc, wellbore_No, "RUN", wellboreId); if (end.Key.Contains("DrillAndCasing")) GeoSummaryReportHelper.DrawingDrillAndCasingInfoTb(end, wellboreId);//繪制基本信息井身結構模塊表格 } } } string headerText = string.Format("{0}總結報告", wellbore_No); GeoSummaryReportHelper.AddHeader(resultDoc, headerText);//添加頁眉 } string url = Request.Url.ToString().Replace(Request.Url.AbsolutePath,""); //返回生成的文檔的信息 string ahref = url + "/OfficeTemp/" + wellbore_No + "/" + HttpContext.User.Identity.Name + "/" + fileName;//Server.MapPath("~/OfficeTemp/") + wellboreId + "/" + HttpContext.User.Identity.Name + "/" + fileName; //Url.Content(Server.MapPath("~/OfficeTemp/")) + wellboreId + "/" + HttpContext.User.Identity.Name + "/" + fileName; string createTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"); string returnValues = string.Format( @"<a href='{0}'>{1}</a> 生成時間:{2}   <a href=javascript:EditReport('{1}')>【編輯】</a>   <a href='javascript:BuildReport()'>【重新生成】</a> <a href='javascript:ExpToZip()'>【打包下載】</a>", ahref, fileName, createTime); return returnValues; // string.Format( // @"<a href='{0}'>{1}</a> // 生成時間:{2}   <a href=javascript:EditReport('{1}')>【編輯】</a> //   <a href='javascript:BuildReport()'>【重新生成】</a> // <a href='javascript:ExpToZip()'>【打包下載】</a> // <a href=javascript:DeleteWellboresById('{3}')>【刪除】</a>", ahref, fileName, createTime, wellboreId); } catch (Exception ex) { throw new Exception(ex.Message); } }
2、替換占位符方法
/// <summary> /// 替換文本 /// </summary> /// <param name="WellboreId"></param> /// <param name="OuterXml"></param> /// <returns></returns> public static string XmlStringReplace(Guid WellboreId, string wellbore_No, string OuterXml, string appendixTypes) { try {string retVal = OuterXml; #region 標題第一頁數據占位符替換 retVal = retVal.Replace("{AREA}", 888); #endregion return retVal; } catch (Exception ex) { throw new ApplicationException(string.Format("替換附表數據失敗:錯誤原因是:{0}", ex.Message)); } }
3、上面還用到一個設置頁眉的方法
/// <summary> /// 添加頁眉 /// </summary> /// <param name="doc">文檔對象</param> /// <param name="HeaderTxt">頁眉標題</param> public static void AddHeader(WordprocessingDocument doc, string HeaderTxt) { countheader = 0; string newHeaderText = HeaderTxt; MainDocumentPart mainDocPart = doc.MainDocumentPart; mainDocPart.DeleteParts(mainDocPart.HeaderParts); HeaderPart newHeaderPart = mainDocPart.AddNewPart<HeaderPart>(); string rId = mainDocPart.GetIdOfPart(newHeaderPart); GeneratePageHeaderPart(newHeaderText).Save(newHeaderPart); foreach (SectionProperties sectProperties in mainDocPart.Document.Descendants<SectionProperties>()) { countheader++; int count=sectProperties.Count(); foreach (HeaderReference headerReference in sectProperties.Descendants<HeaderReference>()) { sectProperties.RemoveChild(headerReference); HeaderReference newHeaderReference = new HeaderReference() {Id = rId, Type = HeaderFooterValues.Default}; sectProperties.Append(newHeaderReference); } } }
4、生成word中還有一個獲取所有書簽的方法
/// <summary> /// 獲取所有書簽 /// </summary> /// <param name="documentPart"></param> /// <param name="results"></param> /// <param name="unmatched"></param> /// <returns></returns> public static Dictionary<string, BookmarkEnd> FindBookmarks(OpenXmlElement documentPart, Dictionary<string, BookmarkEnd> results = null, Dictionary<string, string> unmatched = null) { results = results ?? new Dictionary<string, BookmarkEnd>(); unmatched = unmatched ?? new Dictionary<string, string>(); foreach (var child in documentPart.Elements()) { if (child is BookmarkStart) { var bStart = child as BookmarkStart; if (!unmatched.ContainsKey(bStart.Id)) { unmatched.Add(bStart.Id, bStart.Name); } } if (child is BookmarkEnd) { var bEnd = child as BookmarkEnd; foreach (var orphanName in unmatched) { if (bEnd.Id == orphanName.Key && !results.ContainsKey(orphanName.Value)) results.Add(orphanName.Value, bEnd); } } FindBookmarks(child, results, unmatched); } return results; }
更多該組件的歡迎大家一起討論交流。。。。