在前台页面中先插入一个ASPxHtmlEditor控件,名为ASPxHtmlEditor1。 我用的Dev版本为14.1
格式化文本
在后台插入如下代码
1 const string css = "style='text-align:justify;" //两端对齐 2 + "text-justify:inter-ideograph;" 3 + "text-indent: 2em;" //首行缩进2字符 4 + "line-height:1.25;" //1.25倍行距 5 + "margin-top:0;margin-bottom:0;" //段前段后0行 6 + "font-size: 12pt;" //字体:小四 7 + "font-family:Times New Roman,宋体;'"; //中文字体:宋体,西文字体:Times New Roman 8 9 ASPxHtmlEditor1.Html = "<p " + css + ">"; //段落用标签p标记 for (int i = ; i < ;i++) ASPxHtmlEditor1.Html += "测试文本123abCD"; //这是内容 ASPxHtmlEditor1.Html += "</p>
上述代码实现了对文字的格式化,可以基本满足生成一般报告的格式需要。
Word导出及页面设置
对于ASPxHtmlEditor控件,无法直接设置导出Word或其他格式文件的页面(页边距、纸张大小等),需借助RichEditDocumentServer来转存实现。
添加如下引用:
using DevExpress.XtraRichEdit; using DevExpress.XtraRichEdit.API.Native;
插入下面两个函数
1 private void SetPrintOptions(IRichEditDocumentServer richedit) //设置格式
2 { 3 foreach (Section _section in richedit.Document.Sections) 4 { 5 _section.Page.PaperKind = System.Drawing.Printing.PaperKind.A4; //A4纸 6 _section.Page.Landscape = false; //竖版 7 _section.Margins.Left = 295f; //左侧页边距 2.5cm 8 _section.Margins.Right = 295f; 9 _section.Margins.Top = 295f; _section.Margins.Bottom = 295f; } } protected void PushToBrowser(string fileName) //导出文件 { FileStream fs = new FileStream(fileName, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, , bytes.Length); fs.Close(); if (File.Exists(fileName)) File.Delete(fileName); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); Response.BinaryWrite(bytes); Response.Flush(); Response.End(); }
在执行导出的事件(如Button_Click事件)中添加如下代码
1 string outputFileName = "newtext.doc"; //导出文件的名称
2 3 FileStream fs = new FileStream("test.rtf", FileMode.Create); 4 ASPxHtmlEditor1.Export(DevExpress.Web.ASPxHtmlEditor.HtmlEditorExportFormat.Rtf, fs); //注意此处 先导出Rtf格式 5 fs.Close(); 6 fs.Close(); 7 8 RichEditDocumentServer srv = new RichEditDocumentServer(); 9 srv.LoadDocument("test.rtf", DocumentFormat.Rtf); srv.BeginUpdate(); SetPrintOptions(srv); srv.EndUpdate(); srv.SaveDocument(outputFileName, DocumentFormat.Doc); //再导出Doc格式 如果导出OpenXml(.Docx)格式,则中文字体丢失
if (File.Exists("test.rtf")) File.Delete("test.rtf"); PushToBrowser(outputFileName);
输出的文本如下:

p.s.关于页边距设置成cm的换算
试了几组数据,做了个3次拟合,先凑合用吧。(x是期望设置的厘米数 如2.5cm y就是程序的中用到的参数 如295 )