I want to set a RTL direction for some cell of a table that I create with OpenXml.
row.Append(
new TableCell(
new Paragraph(
new Run(
new Text("FullName")))){
TableCellProperties = new TableCellProperties()
{
TableCellWidth = new TableCellWidth(){
Type = TableWidthUnitValues.Dxa,
Width = "3400" },
TextDirection = new TextDirection(){
Val = new EnumValue<TextDirectionValues>(TextDirectionValues.TopToBottomRightToLeft)}
}
});
I wrote this code, but TextDirectionValues Enum dosen't have a RTL value.
If your tables are like this:
TableRow > TableCell > Paragraph > Run > Text.
This code may help you:
//Justification
aRow.Descendants<TableCell>().ElementAt(indx).Descendants<Paragraph>()
.ElementAt(0).ParagraphProperties = new ParagraphProperties()
{
Justification = new Justification()
{
Val = new EnumValue<JustificationValues>(JustificationValues.Right)
}
};
//RightToLeftText
foreach (var r in aRow.Descendants<TableCell>().ElementAt(indx).Descendants<Run>())
{
r.RunProperties = new RunProperties()
{
RightToLeftText = new RightToLeftText()
{
Val = new OnOffValue(true)
}
};
}
Related
I want to create pie chart on Excel using OpenXml. Is there any source from where i can get help?.
I have already developed the Bar Chart.
Here's my reference:
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using C = DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using DocumentFormat.OpenXml.Drawing;
I'm using here MemoryStream to create excel file:
WorkbookPart workbookPart = null;
using (var memoryStream = new MemoryStream())
{
using (var excel = SpreadsheetDocument.Create(memoryStream, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook, true))
{
workbookPart = excel.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>("rId1");
Worksheet worksheet = new Worksheet();
SheetData sheetData = new SheetData();
worksheet.Append(sheetData);
worksheetPart.Worksheet = worksheet;
string relationshipId = "rId1";// workbookPart.GetIdOfPart(worksheetPart);
Sheets sheets = new Sheets();
uint sheetId = 1;
string sheetName = "Sheet" + sheetId;
Sheet sheet1 = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet1);
workbookPart.Workbook.Append(sheets);
//// Add a new drawing to the worksheet.
DrawingsPart drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
worksheetPart.Worksheet.Append(new DocumentFormat.OpenXml.Spreadsheet.Drawing()
{
Id = worksheetPart.GetIdOfPart(drawingsPart)
});
worksheetPart.Worksheet.Save();
string chartTitle = "Generator Utilisation";
Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("Running", 92);
data.Add("Stopped", 8);
InsertPieChartInSpreadSheet(drawingsPart, chartTitle, data, 1, 1, 17, 8);
excel.Close();
}
FileStream fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "Plant Summary Report.xlsx", FileMode.Create, FileAccess.Write);
memoryStream.WriteTo(fileStream);
fileStream.Close();
memoryStream.Close();
}
Here is InsertPieChartInSpreadSheet method:
private static void InsertPieChartInSpreadSheet(DrawingsPart drawingsPart,string chartTitle, Dictionary<string, int> data, int startRowIndex, int startColumnIndex, int endRowIndex, int endColumnIndex)
{
ChartPart chartPart = drawingsPart.AddNewPart<ChartPart>();
ChartSpace chartSpace = new ChartSpace();
chartSpace.Append(new EditingLanguage() { Val = new StringValue("en-US") });
DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartSpace.AppendChild<DocumentFormat.OpenXml.Drawing.Charts.Chart>(
new DocumentFormat.OpenXml.Drawing.Charts.Chart());
PlotArea plotArea = chart.AppendChild<PlotArea>(new PlotArea());
Layout layout = plotArea.AppendChild<Layout>(new Layout());
ManualLayout manualLayout1 = new ManualLayout();
LayoutTarget layoutTarget1 = new LayoutTarget() { Val = LayoutTargetValues.Inner };
LeftMode leftMode1 = new LeftMode() { Val = LayoutModeValues.Edge };
TopMode topMode1 = new TopMode() { Val = LayoutModeValues.Edge };
Left left1 = new Left() { Val = 0.5D };
Top top1 = new Top() { Val = 0.2D };
Width width1 = new Width() { Val = 0.95622038461448768D };
Height height1 = new Height() { Val = 0.54928769841269842D };
manualLayout1.Append(layoutTarget1);
manualLayout1.Append(leftMode1);
manualLayout1.Append(topMode1);
manualLayout1.Append(left1);
manualLayout1.Append(top1);
manualLayout1.Append(width1);
manualLayout1.Append(height1);
layout.Append(manualLayout1);
NoFill noFill = new NoFill();
C.ShapeProperties shapeProperties = new C.ShapeProperties();
DocumentFormat.OpenXml.Drawing.Outline outline15 = new DocumentFormat.OpenXml.Drawing.Outline();
DocumentFormat.OpenXml.Drawing.SolidFill noFill17 = new DocumentFormat.OpenXml.Drawing.SolidFill();
RgbColorModelHex schemeColor29 = new RgbColorModelHex() { Val = "FFFFFF" };
noFill17.Append(schemeColor29);
outline15.Append(noFill17);
shapeProperties.Append(noFill);
shapeProperties.Append(outline15);
plotArea.Append(shapeProperties);
PieChart pieChart = plotArea.AppendChild<PieChart>(new PieChart());
PieChartSeries pieChartSeries = pieChart.AppendChild<PieChartSeries>(new PieChartSeries(
new Index() { Val = (UInt32Value)0U },
new Order() { Val = (UInt32Value)0U },
new SeriesText(new NumericValue() { Text = "PieChartSeries" })));
CategoryAxisData catAx = new CategoryAxisData();
StringReference stringReference = new StringReference();
StringCache stringCache = new StringCache();
PointCount pointCount = new PointCount() { Val = (uint)data.Count };
stringCache.Append(pointCount);
uint i = 0;
foreach (var key in data.Keys)
{
stringCache.AppendChild<StringPoint>(new StringPoint() { Index = new UInt32Value(i) }).Append(new NumericValue(key));
i++;
}
stringReference.Append(stringCache);
catAx.Append(stringReference);
pieChartSeries.Append(catAx);
C.Values values = new C.Values();
NumberReference numberReference = new NumberReference();
NumberingCache numberingCache = new NumberingCache();
i = 0;
foreach (var key in data.Keys)
{
numberingCache.AppendChild<NumericPoint>(new NumericPoint() { Index = new UInt32Value(i) }).Append(new NumericValue(data[key].ToString()));
i++;
}
numberReference.Append(numberingCache);
values.Append(numberReference);
pieChartSeries.Append(values);
AddChartTitle(chart, chartTitle);
pieChart.Append(new AxisId() { Val = new UInt32Value(48650112u) });
pieChart.Append(new AxisId() { Val = new UInt32Value(48672768u) });
CategoryAxis catAx1 = plotArea.AppendChild<CategoryAxis>(new CategoryAxis(new AxisId()
{ Val = new UInt32Value(48650112u) }, new Scaling(new Orientation()
{
Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Bottom) },
new TickLabelPosition() { Val = new EnumValue<TickLabelPositionValues>(TickLabelPositionValues.NextTo) },
new CrossingAxis() { Val = new UInt32Value(48672768U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new AutoLabeled() { Val = new BooleanValue(true) },
new LabelAlignment() { Val = new EnumValue<LabelAlignmentValues>(LabelAlignmentValues.Center) },
new LabelOffset() { Val = new UInt16Value((ushort)100) }));
// Add the Value Axis.
ValueAxis valAx = plotArea.AppendChild<ValueAxis>(new ValueAxis(new AxisId() { Val = new UInt32Value(48672768u) },
new Scaling(new Orientation()
{
Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(
DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax)
}),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Left) },
new MajorGridlines(),
new DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat()
{
FormatCode = new StringValue("General"),
SourceLinked = new BooleanValue(true)
}, new TickLabelPosition()
{
Val = new EnumValue<TickLabelPositionValues>
(TickLabelPositionValues.NextTo)
}, new CrossingAxis() { Val = new UInt32Value(48650112U) },
new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) },
new CrossBetween() { Val = new EnumValue<CrossBetweenValues>(CrossBetweenValues.Between) }));
// Add the chart Legend.
Legend legend = chart.AppendChild<Legend>(new Legend(new LegendPosition() { Val = new EnumValue<LegendPositionValues>(LegendPositionValues.Bottom) },
new Layout()));
chart.Append(new PlotVisibleOnly() { Val = new BooleanValue(true) });
chartPart.ChartSpace = chartSpace;
PositionChart(chartPart, drawingsPart, startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);
}
Here's an additional method which will set chart position:
private static void PositionChart(ChartPart chartPart, DrawingsPart drawingsPart, int startRowIndex, int startColumnIndex, int endRowIndex, int endColumnIndex)
{
// Position the chart on the worksheet using a TwoCellAnchor object.
drawingsPart.WorksheetDrawing = new WorksheetDrawing();
TwoCellAnchor twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild<TwoCellAnchor>(new TwoCellAnchor());
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(new ColumnId(startColumnIndex.ToString()),
new ColumnOffset("581025"),
new RowId(startRowIndex.ToString()),
new RowOffset("114300")));
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(new ColumnId(endColumnIndex.ToString()),
new ColumnOffset("276225"),
new RowId(endRowIndex.ToString()),
new RowOffset("0")));
// Append a GraphicFrame to the TwoCellAnchor object.
DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame graphicFrame =
twoCellAnchor.AppendChild<DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame>(new DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame());
graphicFrame.Macro = "";
graphicFrame.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameProperties(
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties() { Id = new UInt32Value(2u), Name = "Chart 1" },
new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameDrawingProperties()));
graphicFrame.Append(new Transform(new Offset() { X = 0L, Y = 0L },
new Extents() { Cx = 0L, Cy = 0L }));
graphicFrame.Append(new Graphic(new GraphicData(new ChartReference() { Id = drawingsPart.GetIdOfPart(chartPart) })
{ Uri = "http://schemas.openxmlformats.org/drawingml/2006/chart" }));
twoCellAnchor.Append(new ClientData());
}
This method will add chart title:
private static void AddChartTitle(DocumentFormat.OpenXml.Drawing.Charts.Chart chart, string title)
{
var ctitle = chart.AppendChild(new Title());
var chartText = ctitle.AppendChild(new ChartText());
var richText = chartText.AppendChild(new RichText());
var bodyPr = richText.AppendChild(new BodyProperties());
var lstStyle = richText.AppendChild(new ListStyle());
var paragraph = richText.AppendChild(new Paragraph());
var apPr = paragraph.AppendChild(new ParagraphProperties());
apPr.AppendChild(new DefaultRunProperties());
var run = paragraph.AppendChild(new DocumentFormat.OpenXml.Drawing.Run());
run.AppendChild(new DocumentFormat.OpenXml.Drawing.RunProperties() { Language = "en-CA" });
run.AppendChild(new DocumentFormat.OpenXml.Drawing.Text() { Text = title });
//ctitle.AppendChild(new Overlay() { Val = new BooleanValue(false) });
}
I am recently trying to create a bar chart in excel using Open XML and C#.
Below is portion of the script that helped me to create a bar chart in excel.
// Add a new drawing to the worksheet.
DrawingsPart drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
worksheetPart.Worksheet.Append(new DocumentFormat.OpenXml.Spreadsheet.Drawing() { Id = worksheetPart.GetIdOfPart(drawingsPart) });
worksheetPart.Worksheet.Save();
// Add a new chart and set the chart language to English-US.
ChartPart chartPart = drawingsPart.AddNewPart<ChartPart>();
chartPart.ChartSpace = new ChartSpace();
chartPart.ChartSpace.Append(new EditingLanguage() { Val = new StringValue("en-US") });
Drawing.Charts.Chart chart = chartPart.ChartSpace.AppendChild<Drawing.Charts.Chart>(new Drawing.Charts.Chart());
addChartTitle(chart, chartTitleText);
// Create a new clustered column chart.
PlotArea plotArea = chart.AppendChild<PlotArea>(new PlotArea());
Layout layout = plotArea.AppendChild<Layout>(new Layout());
addBarchart(plotArea);
addCategoryAxis(plotArea);
// Add the Value Axis.
ValueAxis valAx = plotArea.AppendChild<ValueAxis>(new ValueAxis(new AxisId() { Val = new UInt32Value(48672768u) },
new Scaling(new Orientation() { Val = new EnumValue<DocumentFormat.OpenXml.Drawing.Charts.OrientationValues>(DocumentFormat.OpenXml.Drawing.Charts.OrientationValues.MinMax) }),
new AxisPosition() { Val = new EnumValue<AxisPositionValues>(AxisPositionValues.Left) }, new MajorGridlines(), new DocumentFormat.OpenXml.Drawing.Charts.NumberingFormat()
{ FormatCode = new StringValue("General"), SourceLinked = new BooleanValue(true) }, new TickLabelPosition() { Val = new EnumValue<TickLabelPositionValues> (TickLabelPositionValues.NextTo) },
new CrossingAxis() { Val = new UInt32Value(48650112U) }, new Crosses() { Val = new EnumValue<CrossesValues>(CrossesValues.AutoZero) }, new CrossBetween() { Val = new EnumValue<CrossBetweenValues>(CrossBetweenValues.Between) }));
But unfortunately when I tried to edit the colors of bars, I couldn't make it successful. Please help me create a chart and to update chart properties using Open XML and C#.
I need to create a Word Document using Open XML SDK. I have the document text and the Footnotes . I am using the below Snippets to Create the Word Document.
I am able to create the document with the text ,But I am not able to add Footnotes to it.
Can you please let us know how to add FootNotes programmatically using Open Xml
public void CreateWordDocument()
{
using (MemoryStream DocxMemory = new MemoryStream())
{
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(DocxMemory, WordprocessingDocumentType.Document, true))
{
// Add a main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create the document structure and add some text.
this.AddSettingsToMainDocumentPart(mainPart);
StyleDefinitionsPart part = mainPart.StyleDefinitionsPart;
// If the Styles part does not exist, add it.
if (part == null)
{
this.AddStylesPartToPackage(mainPart);
}
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph Para = body.AppendChild(new Paragraph());
Run run = Para.AppendChild(new Run());
run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("This is main text of the document"));
var footnotesPart = mainPart.AddNewPart<FootnotesPart>("rId1");
this.GenerateFooterPartContent(mainPart.FootnotesPart);
mainPart.Document.Save();
wordDocument.Close();
MemoryStream Result = new MemoryStream();
DocxMemory.Seek(0, SeekOrigin.Begin);
DocxMemory.CopyTo(Result);
Result.Position = 0;
////Citation processing
byte[] BufferFileData = new byte[Result.Length];
Result.Read(BufferFileData, 0, (int)Result.Length);
File.WriteAllBytes("Output1.docx", BufferFileData);
}
}
}
private void AddSettingsToMainDocumentPart(MainDocumentPart part)
{
DocumentSettingsPart settingsPart = part.DocumentSettingsPart;
if (settingsPart == null)
settingsPart = part.AddNewPart<DocumentSettingsPart>();
settingsPart.Settings = new Settings(
new Compatibility(
new CompatibilitySetting()
{
Name = new EnumValue<CompatSettingNameValues>
(CompatSettingNameValues.CompatibilityMode),
Val = new StringValue("14"),
Uri = new StringValue
("http://schemas.microsoft.com/office/word")
}
)
);
settingsPart.Settings.Save();
}
private StyleDefinitionsPart AddStylesPartToPackage(MainDocumentPart mainPart)
{
StyleDefinitionsPart part;
part = mainPart.AddNewPart<StyleDefinitionsPart>();
Styles root = new Styles();
root.Save(part);
return part;
}
// Generates content of part.
private void GenerateFooterPartContent(FootnotesPart part)
{
Footnotes footnotes1 = new Footnotes() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
footnotes1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
footnotes1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
footnotes1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
footnotes1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
footnotes1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
footnotes1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
footnotes1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
footnotes1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
footnotes1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
footnotes1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
footnotes1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
footnotes1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
footnotes1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
footnotes1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
footnotes1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
Footnote footnote1 = new Footnote() { Type = FootnoteEndnoteValues.Separator, Id = -1 };
Paragraph paragraph1 = new Paragraph() { RsidParagraphAddition = "003F1A60", RsidParagraphProperties = "00626544", RsidRunAdditionDefault = "003F1A60" };
Run run1 = new Run();
SeparatorMark separatorMark1 = new SeparatorMark();
run1.Append(separatorMark1);
paragraph1.Append(run1);
footnote1.Append(paragraph1);
Footnote footnote2 = new Footnote() { Type = FootnoteEndnoteValues.ContinuationSeparator, Id = 0 };
Paragraph paragraph2 = new Paragraph() { RsidParagraphAddition = "003F1A60", RsidParagraphProperties = "00626544", RsidRunAdditionDefault = "003F1A60" };
Run run2 = new Run();
ContinuationSeparatorMark continuationSeparatorMark1 = new ContinuationSeparatorMark();
run2.Append(continuationSeparatorMark1);
paragraph2.Append(run2);
footnote2.Append(paragraph2);
Footnote footnote3 = new Footnote() { Id = 1 };
Paragraph paragraph3 = new Paragraph() { RsidParagraphMarkRevision = "009774CC", RsidParagraphAddition = "00626544", RsidParagraphProperties = "00626544", RsidRunAdditionDefault = "00626544" };
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
RunFonts runFonts1 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
FontSize fontSize1 = new FontSize() { Val = "24" };
FontSizeComplexScript fontSizeComplexScript1 = new FontSizeComplexScript() { Val = "24" };
paragraphMarkRunProperties1.Append(runFonts1);
paragraphMarkRunProperties1.Append(fontSize1);
paragraphMarkRunProperties1.Append(fontSizeComplexScript1);
paragraphProperties1.Append(paragraphMarkRunProperties1);
Run run3 = new Run() { RsidRunProperties = "009774CC" };
RunProperties runProperties1 = new RunProperties();
RunFonts runFonts2 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
FontSize fontSize2 = new FontSize() { Val = "24" };
FontSizeComplexScript fontSizeComplexScript2 = new FontSizeComplexScript() { Val = "24" };
VerticalTextAlignment verticalTextAlignment1 = new VerticalTextAlignment() { Val = VerticalPositionValues.Superscript };
runProperties1.Append(runFonts2);
runProperties1.Append(fontSize2);
runProperties1.Append(fontSizeComplexScript2);
runProperties1.Append(verticalTextAlignment1);
Text text1 = new Text();
text1.Text = "1";
run3.Append(runProperties1);
run3.Append(text1);
Run run4 = new Run() { RsidRunProperties = "009774CC" };
RunProperties runProperties2 = new RunProperties();
RunFonts runFonts3 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
runProperties2.Append(runFonts3);
Text text2 = new Text() { Space = SpaceProcessingModeValues.Preserve };
text2.Text = " ";
run4.Append(runProperties2);
run4.Append(text2);
Run run5 = new Run() { RsidRunProperties = "009774CC", RsidRunAddition = "009774CC" };
RunProperties runProperties3 = new RunProperties();
RunFonts runFonts4 = new RunFonts() { AsciiTheme = ThemeFontValues.MinorHighAnsi, HighAnsiTheme = ThemeFontValues.MinorHighAnsi, ComplexScriptTheme = ThemeFontValues.MinorHighAnsi };
FontSize fontSize3 = new FontSize() { Val = "21" };
FontSizeComplexScript fontSizeComplexScript3 = new FontSizeComplexScript() { Val = "21" };
runProperties3.Append(runFonts4);
runProperties3.Append(fontSize3);
runProperties3.Append(fontSizeComplexScript3);
Text text3 = new Text();
text3.Text = "This is the foot note text";
run5.Append(runProperties3);
run5.Append(text3);
paragraph3.Append(paragraphProperties1);
paragraph3.Append(run3);
paragraph3.Append(run4);
paragraph3.Append(run5);
footnote3.Append(paragraph3);
footnotes1.Append(footnote1);
footnotes1.Append(footnote2);
footnotes1.Append(footnote3);
part.Footnotes = footnotes1;
}
I managed to add footnotes using the following code.
I hope this helps.
var ms = new MemoryStream();
using (WordprocessingDocument myDoc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
var footPart = mainPart.AddNewPart<FootnotesPart>();
footPart.Footnotes = new Footnotes();
mainPart.Document = new Document();
Body body = new Body();
var p = new Paragraph();
var r = new Run();
var t = new Text("123");
r.Append(t);
p.Append(r);
// ADD THE FOOTNOTE
var footnote = new Footnote();
footnote.Id = 1;
var p2 = new Paragraph();
var r2 = new Run();
var t2 = new Text();
t2.Text = "My FootNote Content";
r2.Append(t2);
p2.Append(r2);
footnote.Append(p2);
footPart.Footnotes.Append(footnote);
// ADD THE FOOTNOTE REFERENCE
var fref = new FootnoteReference();
fref.Id = 1;
var r3 = new Run();
r3.RunProperties = new RunProperties();
var s3 = new VerticalTextAlignment();
s3.Val = VerticalPositionValues.Superscript;
r3.RunProperties.Append(s3);
r3.Append(fref);
p.Append(r3);
body.Append(p);
mainPart.Document.Append(body);
mainPart.Document.Save();
ms.Flush();
}
return ms.ToArray();
I'm not an expert on OpenXML but I think you're missing adding an actual reference to the footnote in the body text, I tweaked your code like this and I now get the footnote in the document. Hope it helps or at least gets you started.
Run run = Para.AppendChild(new Run());
run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("This is main text of the document"));
var footnoteref = new FootnoteReference() { Id = 1 };
run.Append(footnoteref);
My requirement is : Exporting a dynamic DataTable to Word document with Page Numbers
We need to use Open XML to achieve this.
I have code to export Datatable to Word. And also to insert page numbers.
I got Below code code to export datatable
public void CreateWordtable(string filename,DataTable data)
{
WordprocessingDocument doc = WordprocessingDocument.Create(filename, WordprocessingDocumentType.Document);
MainDocumentPart mainDocPart = doc.AddMainDocumentPart();
mainDocPart.Document = new Document();
Body body = new Body();
mainDocPart.Document.Append(body);
//rinks#::creating new table
DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();
for (int i = 0; i < data.Rows.Count; ++i)
{
TableRow row = new TableRow();
for (int j = 0; j < data.Columns.Count; j++)
{
TableCell cell = new TableCell();
cell.Append(new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(data.Rows[i][j].ToString()))));
cell.Append(new TableCellProperties(new TableCellWidth { Type = TableWidthUnitValues.Dxa, Width = "1200" }));
row.Append(cell);
}
table.Append(row);
}
body.Append(table);
doc.MainDocumentPart.Document.Save();
doc.Dispose();
}
And below code is to insert page numbers in a word document
private static void AddPageNumberFooters(WordprocessingDocument parent)
{
string documentPath = #"D:\EmptyDoc.docx";
using (WordprocessingDocument package =
WordprocessingDocument.Open(documentPath, true))
{
var mainDocumentPart = parent.AddMainDocumentPart();
GenerateMainDocumentPart().Save(mainDocumentPart);
var documentSettingsPart =
mainDocumentPart.AddNewPart
<DocumentSettingsPart>("rId1");
GenerateDocumentSettingsPart().Save(documentSettingsPart);
var firstPageFooterPart = mainDocumentPart.AddNewPart<FooterPart>("rId1");
GeneratePageFooterPart("Page 1 of 2").Save(firstPageFooterPart);
var secondPageFooterPart = mainDocumentPart.AddNewPart<FooterPart>("rId2");
GeneratePageFooterPart("Page 2 of 2").Save(secondPageFooterPart);
}
}
private static Document GenerateMainDocumentPart()
{
var element =
new Document(
new Body(
new Paragraph(
new Run(
new Text("Page 1 content"))
),
new Paragraph(
new Run(
new Break() { Type = BreakValues.Page })
),
new Paragraph(
new Run(
new LastRenderedPageBreak(),
new Text("Page 2 content"))
),
new Paragraph(
new Run(
new Break() { Type = BreakValues.Page })
),
new SectionProperties(
new FooterReference()
{
Type = HeaderFooterValues.First,
Id = "rId1"
},
new FooterReference()
{
Type = HeaderFooterValues.Even,
Id = "rId2"
},
new PageMargin()
{
Top = 1440,
Right = (UInt32Value)1440UL,
Bottom = 1440,
Left = (UInt32Value)1440UL,
Header = (UInt32Value)720UL,
Footer = (UInt32Value)720UL,
Gutter = (UInt32Value)0UL
},
new TitlePage()
)));
return element;
}
private static Header GeneratePageHeaderPart(string HeaderText)
{
var element =
new Header(
new Paragraph(
new ParagraphProperties(
new ParagraphStyleId() { Val = "Header" }),
new Run(
new Text(HeaderText))
));
return element;
}
My problem is, I have combine above both methods to export data along with page numbers.
if we know there are 2 pages in the word document, i can insert 2 FooterParts.
But i don't know how many pages will be created after exporting the data.
try the following code to automatically add page numbers:
private static string GenerateFooterPartContent(WordprocessingDocument package, string text = null)
{
FooterPart footerPart1 = package.MainDocumentPart.FooterParts.FirstOrDefault();
if (footerPart1 == null)
{
footerPart1 = package.MainDocumentPart.AddNewPart<FooterPart>();
}
var relationshipId = package.MainDocumentPart.GetIdOfPart(footerPart1);
// Get SectionProperties and set HeaderReference and FooterRefernce with new Id
SectionProperties sectionProperties1 = new SectionProperties();
FooterReference footerReference2 = new FooterReference() { Type = HeaderFooterValues.Default, Id = relationshipId };
sectionProperties1.Append(footerReference2);
package.MainDocumentPart.Document.Body.Append(sectionProperties1);
Footer footer1 = new Footer();
var r = new Run();
PositionalTab positionalTab2 = new PositionalTab() { Alignment = AbsolutePositionTabAlignmentValues.Right,
RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin,
Leader = AbsolutePositionTabLeaderCharValues.None };
r.Append(positionalTab2);
paragraph2.Append(r);
r = new Run(new Text("Page: ") { Space = SpaceProcessingModeValues.Preserve },
// *** Adaptation: This will output the page number dynamically ***
new SimpleField() { Instruction = "PAGE" },
new Text(" of ") { Space = SpaceProcessingModeValues.Preserve },
// *** Adaptation: This will output the number of pages dynamically ***
new SimpleField() { Instruction = "NUMPAGES" });
paragraph2.Append(r);
footer1.Append(paragraph2);
footerPart1.Footer = footer1;
return relationshipId;
}
I am trying top create a word file with the header and footer and footer must have a Image can any one help me to do that.
I am using Open XML to create word file .
You can try this. You need to create a DocumentResource (Item->Add new) and associate an image.
private static Footer BuildFooter(FooterPart hp, string title)
{
ImagePart ip = hp.AddImagePart(ImagePartType.Jpeg);
string imageRelationshipID = hp.GetIdOfPart(ip);
using (Stream imgStream = ip.GetStream())
{
System.Drawing.Bitmap logo = DocumentResources._default;
logo.Save(imgStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
Footer h = new Footer();
DocumentFormat.OpenXml.Wordprocessing.Paragraph p = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
Run r = new Run();
Drawing drawing = BuildImage(imageRelationshipID, "_default.jpg", 200, 30);
r.Append(drawing);
p.Append(r);
r = new Run();
RunProperties rPr = new RunProperties();
TabChar tab = new TabChar();
Bold b = new Bold();
Color color = new Color { Val = "000000" };
DocumentFormat.OpenXml.Wordprocessing.FontSize sz = new DocumentFormat.OpenXml.Wordprocessing.FontSize {Val = Convert.ToString("40")};
Text t = new Text { Text = title };
rPr.Append(b);
rPr.Append(color);
rPr.Append(sz);
r.Append(rPr);
r.Append(tab);
r.Append(t);
p.Append(r);
h.Append(p);
return h;
}
and to build image
private static Drawing BuildImage(string imageRelationshipID, string imageName, int pixelWidth, int pixelHeight)
{
int emuWidth = (int)(pixelWidth * EMU_PER_PIXEL);
int emuHeight = (int)(pixelHeight * EMU_PER_PIXEL);
Drawing drawing = new Drawing();
d.Wordprocessing.Inline inline = new d.Wordprocessing.Inline { DistanceFromTop = 0, DistanceFromBottom = 0, DistanceFromLeft = 0, DistanceFromRight = 0 };
d.Wordprocessing.Anchor anchor = new d.Wordprocessing.Anchor();
d.Wordprocessing.SimplePosition simplePos = new d.Wordprocessing.SimplePosition { X = 0, Y = 0 };
d.Wordprocessing.Extent extent = new d.Wordprocessing.Extent { Cx = emuWidth, Cy = emuHeight };
d.Wordprocessing.DocProperties docPr = new d.Wordprocessing.DocProperties { Id = 1, Name = imageName };
d.Graphic graphic = new d.Graphic();
d.GraphicData graphicData = new d.GraphicData { Uri = GRAPHIC_DATA_URI };
d.Pictures.Picture pic = new d.Pictures.Picture();
d.Pictures.NonVisualPictureProperties nvPicPr = new d.Pictures.NonVisualPictureProperties();
d.Pictures.NonVisualDrawingProperties cNvPr = new d.Pictures.NonVisualDrawingProperties { Id = 2, Name = imageName };
d.Pictures.NonVisualPictureDrawingProperties cNvPicPr = new d.Pictures.NonVisualPictureDrawingProperties();
d.Pictures.BlipFill blipFill = new d.Pictures.BlipFill();
d.Blip blip = new d.Blip { Embed = imageRelationshipID };
d.Stretch stretch = new d.Stretch();
d.FillRectangle fillRect = new d.FillRectangle();
d.Pictures.ShapeProperties spPr = new d.Pictures.ShapeProperties();
d.Transform2D xfrm = new d.Transform2D();
d.Offset off = new d.Offset { X = 0, Y = 0 };
d.Extents ext = new d.Extents { Cx = emuWidth, Cy = emuHeight };
d.PresetGeometry prstGeom = new d.PresetGeometry { Preset = d.ShapeTypeValues.Rectangle };
d.AdjustValueList avLst = new d.AdjustValueList();
xfrm.Append(off);
xfrm.Append(ext);
prstGeom.Append(avLst);
stretch.Append(fillRect);
spPr.Append(xfrm);
spPr.Append(prstGeom);
blipFill.Append(blip);
blipFill.Append(stretch);
nvPicPr.Append(cNvPr);
nvPicPr.Append(cNvPicPr);
pic.Append(nvPicPr);
pic.Append(blipFill);
pic.Append(spPr);
graphicData.Append(pic);
graphic.Append(graphicData);
inline.Append(extent);
inline.Append(docPr);
inline.Append(graphic);
drawing.Append(inline);
return drawing;
}
To call those functions, in your function that build the document
FooterPart hp = mp.AddNewPart<FooterPart>();
string headerRelationshipID = mp.GetIdOfPart(hp);
SectionProperties sectPr = new SectionProperties();
FooterReference footerReference = new FooterReference();
FooterReference.Id = footerRelationshipID;
FooterReference.Type = HeaderFooterValues.Default;
sectPr.Append(footerReference);
b.Append(sectPr);
d.Append(b);
hp.Footer = BuildFooter(hp, "My Test");