一、前言

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>&nbsp;&nbsp;&nbsp;
生成时间:{2} &nbsp;&nbsp&nbsp;&nbsp;<a href=javascript:EditReport('{1}')>【编辑】</a>
&nbsp;&nbsp&nbsp;&nbsp;<a href='javascript:BuildReport()'>【重新生成】</a>
&nbsp;&nbsp;<a href='javascript:ExpToZip()'>【打包下载】</a>", ahref, fileName, createTime);
return returnValues;
// string.Format(
// @"<a href='{0}'>{1}</a>&nbsp;&nbsp;&nbsp;
// 生成时间:{2} &nbsp;&nbsp&nbsp;&nbsp;<a href=javascript:EditReport('{1}')>【编辑】</a>
// &nbsp;&nbsp&nbsp;&nbsp;<a href='javascript:BuildReport()'>【重新生成】</a>
// &nbsp;&nbsp;<a href='javascript:ExpToZip()'>【打包下载】</a>
// &nbsp;&nbsp;<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 = ;
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;
}

更多该组件的欢迎大家一起讨论交流。。。。

最新文章

  1. Ext分页实现(前台与后台)
  2. jQuery Datepicker日期控件
  3. Perl技巧
  4. LDPC编译码基本原理
  5. POJ3493 Largest Submatrix of All 1’s(单调栈)
  6. Spark Job Scheduling
  7. XCode模拟器屏幕显示内容非常慢
  8. 对config配置文件的读取和修改
  9. 【定位:PDF文件定位关键字所在坐标和页码】
  10. Vue2.0 探索之路——生命周期和钩子函数
  11. 网页设计入门&lt;一&gt;
  12. docker 基础
  13. (转)springcloud(一):大话Spring Cloud
  14. kickstart-E
  15. js获取当前日期(年月日格式)
  16. 使用Java语言开发机器学习框架和参数服务器
  17. spring 自定义事物同步器(一): TransactionSynchronizationManager 解析
  18. mybatis缓存有关的设置和属性
  19. ORACLE11g 没有控制文件如何通过rman备份恢复数据的详细实战过程
  20. 第七周作业——简单FTP

热门文章

  1. onbeforeunload事件
  2. VS2013启动越来越慢
  3. Visual Studio下使用NUnit进行测试驱动开发
  4. nowcoder(牛客网)普及组模拟赛第一场 解题报告
  5. 201621123012《Java程序设计》第10次学习总结
  6. Ubuntu16.04中把默认JAVA设置为Oracle的JDK!
  7. collections中的defaultdict
  8. 在红帽RHEL7.0里配置网卡的四种方法
  9. 事件委托,元素节点操作,todolist计划列表实例
  10. python difflib详解