利用 Open XML 创建了一个带目录的 WORD 文档,如上图 想让生成的目录带有页码信息,求大神指教。
代码下载地址:http://pan.baidu.com/s/1kTILhIn
主要代码如下:
using W = DocumentFormat.OpenXml.Wordprocessing;
using M = DocumentFormat.OpenXml.Math;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
namespace OpenXmlTest
{
public class OpenXMLHelper
{
public WordprocessingDocument wDoc;
public MainDocumentPart mainDoc;
public W.Body body;
public W.Document doc;
public static int titleNum = 988888;
public static string fontName = "微软雅黑";
//四号字,对应word中的大小是10.5(Ps:这是openxml的一个不好之处就是,单位和word中显示的不一致)
public static string fontSize = "21";
//标题字体大小
public static string titleFontSize = "24";
/// <summary>
/// 初始化文档
/// </summary>
/// <param name="fileName">创建文档的路径名称</param>
public void Init(string fileName)
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
wDoc = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document);
mainDoc = wDoc.AddMainDocumentPart();
doc = new W.Document();
body = new W.Body();
}
/// <summary>
/// 添加标题
/// </summary>
/// <param name="text">标题内容</param>
/// <param name="level">标题等级</param>
public void AddTitle(string text, int level)
{
titleNum++;
W.Paragraph paragraph = new W.Paragraph();
W.ParagraphProperties paragraphPraperties = new W.ParagraphProperties();
W.ParagraphStyleId paragraphStyleId = new W.ParagraphStyleId() { Val = level.ToString() };
//修饰段落
W.ParagraphMarkRunProperties paragraphMarkRunProperties = new W.ParagraphMarkRunProperties();
//字体
W.RunFonts runFonts1 = new W.RunFonts() { Ascii = fontName, HighAnsi = fontName, EastAsia = fontName };
//字的大小
W.FontSize fontSize1 = new W.FontSize() { Val = OpenXMLHelper.fontSize };
paragraphMarkRunProperties.Append(runFonts1);
paragraphMarkRunProperties.Append(fontSize1);
paragraphPraperties.Append(paragraphStyleId);
paragraphPraperties.Append(paragraphMarkRunProperties);
W.BookmarkStart bookmarkStart1 = new W.BookmarkStart() { Name = "_Toc" + titleNum, Id = titleNum.ToString() };
W.Run run = new W.Run();
W.RunProperties runProperties = new W.RunProperties();
W.RunFonts runFonts = new W.RunFonts() { Hint = W.FontTypeHintValues.EastAsia, Ascii = fontName, HighAnsi = fontName, EastAsia = fontName };
W.FontSize fontSize = new W.FontSize() { Val = titleFontSize };
runProperties.Append(runFonts);
runProperties.Append(fontSize);
W.LastRenderedPageBreak lrp = new W.LastRenderedPageBreak();
W.Text text1 = new W.Text();
text1.Text = text;
run.Append(runProperties);
run.Append(lrp);
run.Append(text1);
W.BookmarkEnd bookmarkEnd1 = new W.BookmarkEnd { Id = titleNum.ToString() };
paragraph.Append(paragraphPraperties);
paragraph.Append(bookmarkStart1);
paragraph.Append(run);
paragraph.Append(bookmarkEnd1);
body.Append(paragraph);
}
//添加目录
public void AddContents()
{
List<W.Paragraph> paragrap = new List<W.Paragraph>();
#region 查找到所有带有书签的段落
IEnumerable<W.Paragraph> paraGraphs = body.Descendants<W.Paragraph>();
foreach (W.Paragraph para in paraGraphs)
{
if (para.Elements<W.BookmarkStart>().Count() > 0)
{
paragrap.Add(para);
}
}
#endregion
#region 根据查找到带有书签的标题,生成目录
for (int i = 0; i < paragrap.Count; i++)
{
W.Paragraph oldParagraph = paragrap[i];
W.BookmarkStart bs = oldParagraph.Descendants<W.BookmarkStart>().First();
W.ParagraphStyleId ps = oldParagraph.Descendants<W.ParagraphStyleId>().First();
W.Text oldText = oldParagraph.Descendants<W.Text>().First();
#region 创建目录
W.Paragraph newParagraph = new W.Paragraph();
W.ParagraphProperties paragraphProperties1 = new W.ParagraphProperties();
//假设标题对应的格式是标题1,则目录中应该为10
W.ParagraphStyleId paragraphStyleId = new W.ParagraphStyleId() { Val = ps.Val + 0 };
W.Tabs tabs1 = new W.Tabs();
W.TabStop tapStop1 = new W.TabStop() { Val = W.TabStopValues.Right, Leader = W.TabStopLeaderCharValues.Dot, Position = 8296 };
tabs1.Append(tapStop1);
W.ParagraphMarkRunProperties paragraphMarkRunProtites = new W.ParagraphMarkRunProperties();
W.NoProof noProof1 = new W.NoProof();
paragraphMarkRunProtites.Append(noProof1);
paragraphProperties1.Append(paragraphStyleId);
paragraphProperties1.Append(tabs1);
paragraphProperties1.Append(paragraphMarkRunProtites);
W.Hyperlink hyperlink1 = new W.Hyperlink() { History = true, Anchor = bs.Name };
W.Run run1 = new W.Run();
W.RunProperties runProperties1 = new W.RunProperties();
W.RunFonts runFonts1 = GenerateRunFonts(fontName);
W.NoProof noProof2 = new W.NoProof();
runProperties1.Append(runFonts1);
runProperties1.Append(noProof2);
W.Text text1 = new W.Text();
text1.Text = oldText.Text;
run1.Append(runProperties1);
run1.Append(text1);
W.Run run2 = new W.Run();
W.RunProperties runProperties2 = new W.RunProperties();
W.NoProof noProof3 = new W.NoProof();
W.WebHidden webHidden1 = new W.WebHidden();
runProperties2.Append(noProof3);
runProperties2.Append(webHidden1);
W.TabChar tabChar1 = new W.TabChar();
run2.Append(runProperties2);
run2.Append(tabChar1);
W.Run run3 = new W.Run();
W.RunProperties runProperties3 = new W.RunProperties();
W.NoProof noProof4 = new W.NoProof();
W.WebHidden webHidden2 = new W.WebHidden();
runProperties3.Append(noProof4);
runProperties3.Append(webHidden2);
W.FieldChar fieldChar1 = new W.FieldChar() { FieldCharType = W.FieldCharValues.Begin };
run3.Append(runProperties3);
run3.Append(fieldChar1);
W.Run run4 = new W.Run();
W.RunProperties runProperties6 = new W.RunProperties();
W.NoProof noProof6 = new W.NoProof();
W.WebHidden webHidden3 = new W.WebHidden();
runProperties6.Append(noProof6);
runProperties6.Append(webHidden3);
W.FieldCode fieldCode4 = new W.FieldCode() { Space = SpaceProcessingModeValues.Preserve };
fieldCode4.Text = "PAGEREF " + bs.Name + "\\h";
run4.Append(runProperties6);
run4.Append(fieldCode4);
W.Run run5 = new W.Run();
W.RunProperties runProperties8 = new W.RunProperties();
W.NoProof noProof8 = new W.NoProof();
W.WebHidden webHidden5 = new W.WebHidden();
runProperties8.Append(noProof8);
runProperties8.Append(webHidden5);
W.FieldChar fieldChar4 = new W.FieldChar() { FieldCharType = W.FieldCharValues.Separate };
run5.Append(runProperties8);
run5.Append(fieldChar4);
W.Run run6 = new W.Run();
W.RunProperties runProperties10 = new W.RunProperties();
W.NoProof noProof10 = new W.NoProof();
W.WebHidden webHidden7 = new W.WebHidden();
runProperties10.Append(noProof10);
runProperties10.Append(webHidden7);
W.FieldChar fieldChar5 = new W.FieldChar() { FieldCharType = W.FieldCharValues.End };
run6.Append(runProperties10);
run6.Append(fieldChar5);
hyperlink1.Append(run1);
hyperlink1.Append(run2);
hyperlink1.Append(run3);
hyperlink1.Append(run4);
hyperlink1.Append(run5);
hyperlink1.Append(run6);
newParagraph.Append(paragraphProperties1);
if (i == 0)
{
//目录是用域做出来的,所以这里首先添加目录域开始代码
AddCodeStart(newParagraph);
}
newParagraph.Append(hyperlink1);
if (i == paragrap.Count - 1)
{
//目录是用域做出来的,所以这里首先添加目录域结束代码
AddCodeEnd(newParagraph);
}
body.InsertAt<W.Paragraph>(newParagraph, i);
#endregion
}
#endregion
}
private void AddCodeEnd(W.Paragraph newParagraph)
{
W.Run run = new W.Run();
W.FieldChar fieldChar = new W.FieldChar() { FieldCharType = W.FieldCharValues.End };
run.Append(fieldChar);
W.Run run1 = new W.Run();
W.Break break1 = new W.Break() { Type = W.BreakValues.Page };
run1.Append(break1);
newParagraph.Append(run);
newParagraph.Append(run1);
}
private void AddCodeStart(W.Paragraph newParagraph)
{
W.Run run1 = new W.Run();
W.FieldChar fieldChar1 = new W.FieldChar() { FieldCharType = W.FieldCharValues.Begin };
run1.Append(fieldChar1);
W.Run run2 = new W.Run();
W.FieldCode fieldCode1 = new W.FieldCode() { Space = SpaceProcessingModeValues.Preserve };
fieldCode1.Text = " ";
run2.Append(fieldCode1);
W.Run run3 = new W.Run();
W.RunProperties runProperties1 = new W.RunProperties();
W.RunFonts runFonts1 = GenerateRunFonts(fontName);
runProperties1.Append(runFonts1);
W.FieldCode fieldCode2 = new W.FieldCode();
fieldCode2.Text = "TOC \\o \"1-3\" \\h \\z \\u";
run3.Append(runProperties1);
run3.Append(fieldCode2);
W.Run run4 = new W.Run();
W.FieldCode fieldCode3 = new W.FieldCode() { Space = SpaceProcessingModeValues.Preserve };
fieldCode3.Text = " ";
run4.Append(fieldCode3);
W.Run run5 = new W.Run();
W.FieldChar fieldChar2 = new W.FieldChar() { FieldCharType = W.FieldCharValues.Separate };
run5.Append(fieldChar2);
newParagraph.Append(run1);
newParagraph.Append(run2);
newParagraph.Append(run3);
newParagraph.Append(run4);
newParagraph.Append(run5);
}
private W.RunFonts GenerateRunFonts(string fontName)
{
W.RunFonts runFonts = new W.RunFonts() { Hint = W.FontTypeHintValues.EastAsia, Ascii = fontName, HighAnsi = fontName, EastAsia = fontName };
return runFonts;
}
#region 创建页面样式
/// <summary>
/// 创建页面样式
/// </summary>
/// <param name="part"></param>
public static void CreateDocStyle(StyleDefinitionsPart part)
{
Styles styles2 = new Styles();
styles2.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
styles2.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
#region //导航窗格 一级目录样式
W.Style style2 = new W.Style() { Type = W.StyleValues.Paragraph, StyleId = "1" };
W.StyleName styleName2 = new W.StyleName() { Val = "heading 1" };
W.BasedOn basedOn1 = new W.BasedOn() { Val = "a" };
W.NextParagraphStyle nextParagraphStyle1 = new W.NextParagraphStyle() { Val = "a" };
W.LinkedStyle linkedStyle1 = new W.LinkedStyle() { Val = "1Char" };
W.UIPriority uIPriority1 = new W.UIPriority() { Val = 9 };
W.PrimaryStyle primaryStyle2 = new W.PrimaryStyle();
W.Rsid rsid1 = new W.Rsid() { Val = "00861388" };
W.StyleParagraphProperties styleParagraphProperties2 = new W.StyleParagraphProperties();
W.KeepNext keepNext1 = new W.KeepNext();
W.KeepLines keepLines1 = new W.KeepLines();
//W.SpacingBetweenLines spacingBetweenLines1 = new W.SpacingBetweenLines() { Before = "50", After = "50", Line = "578", LineRule = W.LineSpacingRuleValues.Auto };
W.OutlineLevel outlineLevel1 = new W.OutlineLevel() { Val = 0 };
styleParagraphProperties2.Append(keepNext1);
styleParagraphProperties2.Append(keepLines1);
//styleParagraphProperties2.Append(spacingBetweenLines1);
styleParagraphProperties2.Append(outlineLevel1);
W.StyleRunProperties styleRunProperties1 = new W.StyleRunProperties();
W.Bold bold1 = new W.Bold();
W.BoldComplexScript boldComplexScript1 = new W.BoldComplexScript();
W.Kern kern2 = new W.Kern() { Val = (UInt32Value)44U };
W.FontSize fontSize2 = new W.FontSize() { Val = "44" };
W.FontSizeComplexScript fontSizeComplexScript2 = new W.FontSizeComplexScript() { Val = "44" };
styleRunProperties1.Append(bold1);
styleRunProperties1.Append(boldComplexScript1);
styleRunProperties1.Append(kern2);
styleRunProperties1.Append(fontSize2);
styleRunProperties1.Append(fontSizeComplexScript2);
style2.Append(styleName2);
style2.Append(basedOn1);
style2.Append(nextParagraphStyle1);
style2.Append(linkedStyle1);
style2.Append(uIPriority1);
style2.Append(primaryStyle2);
style2.Append(rsid1);
style2.Append(styleParagraphProperties2);
style2.Append(styleRunProperties1);
#endregion
#region //导航窗格 二级目录样式
W.Style style3 = new W.Style() { Type = W.StyleValues.Paragraph, StyleId = "2" };
W.StyleName styleName3 = new W.StyleName() { Val = "heading 2" };
W.BasedOn basedOn2 = new W.BasedOn() { Val = "a" };
W.NextParagraphStyle nextParagraphStyle2 = new W.NextParagraphStyle() { Val = "a" };
W.LinkedStyle linkedStyle2 = new W.LinkedStyle() { Val = "2Char" };
W.UIPriority uIPriority2 = new W.UIPriority() { Val = 9 };
W.UnhideWhenUsed unhideWhenUsed1 = new W.UnhideWhenUsed();
W.PrimaryStyle primaryStyle3 = new W.PrimaryStyle();
W.Rsid rsid2 = new W.Rsid() { Val = "00853401" };
W.StyleParagraphProperties styleParagraphProperties3 = new W.StyleParagraphProperties();
W.KeepNext keepNext2 = new W.KeepNext();
W.KeepLines keepLines2 = new W.KeepLines();
//设置行距
//W.SpacingBetweenLines spacingBetweenLines2 = new W.SpacingBetweenLines() { Before = "50", After = "50", Line = "416", LineRule = W.LineSpacingRuleValues.Auto };
W.OutlineLevel outlineLevel2 = new W.OutlineLevel() { Val = 1 };
styleParagraphProperties3.Append(keepNext2);
styleParagraphProperties3.Append(keepLines2);
//styleParagraphProperties3.Append(spacingBetweenLines2);
styleParagraphProperties3.Append(outlineLevel2);
W.StyleRunProperties styleRunProperties2 = new W.StyleRunProperties();
W.RunFonts runFonts2 = new W.RunFonts() { AsciiTheme = W.ThemeFontValues.MajorHighAnsi, HighAnsiTheme = W.ThemeFontValues.MajorHighAnsi, EastAsiaTheme = W.ThemeFontValues.MajorEastAsia, ComplexScriptTheme = W.ThemeFontValues.MajorBidi };
W.Bold bold2 = new W.Bold();
W.BoldComplexScript boldComplexScript2 = new W.BoldComplexScript();
W.FontSize fontSize3 = new W.FontSize() { Val = "32" };
W.FontSizeComplexScript fontSizeComplexScript3 = new W.FontSizeComplexScript() { Val = "32" };
styleRunProperties2.Append(runFonts2);
styleRunProperties2.Append(bold2);
styleRunProperties2.Append(boldComplexScript2);
styleRunProperties2.Append(fontSize3);
styleRunProperties2.Append(fontSizeComplexScript3);
style3.Append(styleName3);
style3.Append(basedOn2);
style3.Append(nextParagraphStyle2);
style3.Append(linkedStyle2);
style3.Append(uIPriority2);
style3.Append(unhideWhenUsed1);
style3.Append(primaryStyle3);
style3.Append(rsid2);
style3.Append(styleParagraphProperties3);
style3.Append(styleRunProperties2);
#endregion
#region //页面 一级目录样式
W.Style style14 = new W.Style() { Type = W.StyleValues.Paragraph, StyleId = "10" };
W.StyleName styleName14 = new W.StyleName() { Val = "toc 1" };
W.BasedOn basedOn10 = new W.BasedOn() { Val = "a" };
W.NextParagraphStyle nextParagraphStyle3 = new W.NextParagraphStyle() { Val = "a" };
W.AutoRedefine autoRedefine1 = new W.AutoRedefine();
W.UIPriority uIPriority13 = new W.UIPriority() { Val = 39 };
W.UnhideWhenUsed unhideWhenUsed7 = new W.UnhideWhenUsed();
W.Rsid rsid10 = new W.Rsid() { Val = "00853401" };
style14.Append(styleName14);
style14.Append(basedOn10);
style14.Append(nextParagraphStyle3);
style14.Append(autoRedefine1);
style14.Append(uIPriority13);
style14.Append(unhideWhenUsed7);
style14.Append(rsid10);
#endregion
#region//页面 二级目录样式
W.Style style15 = new W.Style() { Type = W.StyleValues.Paragraph, StyleId = "20" };
W.StyleName styleName15 = new W.StyleName() { Val = "toc 2" };
W.BasedOn basedOn11 = new W.BasedOn() { Val = "a" };
W.NextParagraphStyle nextParagraphStyle4 = new W.NextParagraphStyle() { Val = "a" };
W.AutoRedefine autoRedefine2 = new W.AutoRedefine();
W.UIPriority uIPriority14 = new W.UIPriority() { Val = 39 };
W.UnhideWhenUsed unhideWhenUsed8 = new W.UnhideWhenUsed();
W.Rsid rsid11 = new W.Rsid() { Val = "00853401" };
style15.Append(styleName15);
style15.Append(basedOn11);
style15.Append(nextParagraphStyle4);
style15.Append(autoRedefine2);
style15.Append(uIPriority14);
style15.Append(unhideWhenUsed8);
style15.Append(rsid11);
#endregion
styles2.Append(style2);//导航窗格 一级目录样式
styles2.Append(style3);//导航窗格 二级目录样式
styles2.Append(style14);//页面 一级目录样式
styles2.Append(style15);//页面 二级目录样式
part.Styles = styles2;
}
#endregion
public void save()
{
doc.Body = body;
mainDoc.Document = doc;
CreateDocStyle(mainDoc.AddNewPart<StyleDefinitionsPart>("rId1"));
wDoc.Close();
}
}
}
问题解决了吗
没有找到解决办法
请问一下现在问题解决了吗?我也遇到了这个问题,实在是不知道如何解决
没有