1、前言javascript
PageOffice是一款幫助Web應用系統或Web網站實現用戶在線編輯Word、Excel、PowerPoint文檔,Word/Excel模板動態填充,Word/Excel在線輸入提交,系統數據導入導出word、excel文檔的Office快速開發組件庫,是目前把Office應用到Web平臺上的最全面、最早進的解決方案。PageOffice爲軟件開發者構建了一套簡潔高效、統一的Office對象接口,同時無縫支持doc、docx、xls、xlsx、ppt、pptx等流行Office文件格式。java
簡而言之就是能夠在線編寫office文件的產品。數據庫
2、安裝PageOffice服務器
專業版試用序列號: 2C697-4FC8-F274-3DD88app
1. 雙擊運行Setup.exe安裝服務器組件。(能夠到官網下載安裝程序)工具
2. 若是運行示例,用VS.Net打開MvcApplication4.sln便可運行。 網站
3. 若是新建網站或集成PageOffice到您現有的網站裏: ui
1). 雙擊運行Setup.exe安裝服務器組件; url
2). 拷貝「集成文件」目錄下的「pageoffice」文件夾到您本身網站的根目錄下; spa
2). VS.NET工具箱拖放PageOffice控件,雙擊控件,在事件代碼中編寫代碼。
------個人項目是.net MVC4 直接把 「pageoffice」文件夾放到本身網站的根目錄下;
3、使用
使用就分爲編輯一個指定路徑下的文件,並保存
一、在網中打開一個指定路徑下的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(); }
二、保存編輯後的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(); }
4、根據數據庫動態生成word文件
生成word並非pageoffice的功能,可是會一塊兒與該組件一塊兒使用
一、生成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); } }
二、替換佔位符方法
/// <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)); } }
三、上面還用到一個設置頁眉的方法
/// <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); } } }
四、生成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; }
更多該組件的歡迎你們一塊兒討論交流。。。。