DOCX: Программное редактирование существующего DOCX документа с использованием редактора низкого уровня
В этом разделе
Класс
DocxDocumentEditor представляет собой редактор низкого уровня для существующего DOCX документа, т.е. класс позволяет редактировать DOCX документ с точки зрения документа Open XML.
Класс
DocxDocumentEditor предназначен для быстрой и простой разработки генератора отчетов/счетов на основе шаблона DOCX документа.
Если вы хотите создать отчет/счет в формате DOCX, вам необходимо выполнить следующие шаги:
-
Откройте Microsoft Word:
- Создайте новый DOCX документ или откройте существующий DOCX документ. Документ DOCX будет использоваться в качестве шаблона для отчета/счета.
- Изменить содержимое DOCX документа. Документ должен содержать всю необходимую разметку, кроме динамических данных. Места для динамических данных должны быть отмечены уникальными текстовыми константами.
-
В коде:
- Откройте документ-шаблон с помощью класса DocxDocumentEditor и добавьте в документ динамические данные (замените текст, вставьте строки таблицы, замените изображения и т. д.).
- Сохраните измененный документ в DOCX файл с помощью метода OpenXmlDocumentEditor.Save или экспортируйте измененный документ с помощью метода OpenXmlDocumentEditor.Export в любой формат, поддерживаемый VintaSoft Imaging SDK (PDF, PDF/A, TIFF, ...).
Проект "Report Generator Demo"
содержит несколько примеров, демонстрирующих, как создавать отчеты на основе DOCX шаблона.
Класс DocxDocumentEditor
Класс
DocxDocumentEditor позволяет:
Класс OpenXmlDocumentElement
OpenXmlDocumentElement представляет базовый класс для всех элементов в DOCX или XLSX документе и позволяет:
Вот C#/VB.NET код, который демонстрирует, как найти и заменить текст в DOCX документе (в примере используется документ-шаблон
FindAndReplaceText_template.docx
):
public static void DocxFindAndReplaceTextExample()
{
string templateFilename = "FindAndReplaceText_template.docx";
string outFilename = "FindAndReplaceText.docx";
string outPdfFilename = "FindAndReplaceText.pdf";
// create DocxDocumentEditor that allows to edit file "FindAndReplaceText_template.docx"
using (Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor editor =
new Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor(templateFilename))
{
// get document body
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentElement documentBody = editor.Body;
// replace first occurrence of text "[field1]" by text "value1"
documentBody["[field1]"] = "value1";
// replace all occurrences of text "[field2]" by text "value2"
documentBody.ReplaceText("[field2]", "value2");
// find text content that corresponds to the text "[field3]"
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextContent field3Content = documentBody.FindText("[field3]");
// change text in found text content
field3Content.Text = "value3";
// replace text "[multiline_field]" by multiline text
documentBody["[multiline_field]"] = "\nline1\nline2\nline3";
// save changed document to a DOCX file
editor.Save(outFilename);
// export changed document to a PDF document
editor.Export(outPdfFilename);
}
}
Public Shared Sub DocxFindAndReplaceTextExample()
Dim templateFilename As String = "FindAndReplaceText_template.docx"
Dim outFilename As String = "FindAndReplaceText.docx"
Dim outPdfFilename As String = "FindAndReplaceText.pdf"
' create DocxDocumentEditor that allows to edit file "FindAndReplaceText_template.docx"
Using editor As New Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor(templateFilename)
' get document body
Dim documentBody As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentElement = editor.Body
' replace first occurrence of text "[field1]" by text "value1"
documentBody("[field1]") = "value1"
' replace all occurrences of text "[field2]" by text "value2"
documentBody.ReplaceText("[field2]", "value2")
' find text content that corresponds to the text "[field3]"
Dim field3Content As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextContent = documentBody.FindText("[field3]")
' change text in found text content
field3Content.Text = "value3"
' replace text "[multiline_field]" by multiline text
documentBody("[multiline_field]") = vbLf & "line1" & vbLf & "line2" & vbLf & "line3"
' save changed document to a DOCX file
editor.Save(outFilename)
' export changed document to a PDF document
editor.Export(outPdfFilename)
End Using
End Sub
Класс OpenXmlTextContent
OpenXmlTextContent представляет текстовое содержимое DOCX или XLSX документа и позволяет:
Вот C#/VB.NET код, который демонстрирует, как изменять свойства текста текстового содержимого (в примере используется шаблон документа
ChangeTextProperties_template.docx
):
public static void DocxChangeTextPropertiesExample()
{
string templateFilename = "ChangeTextProperties_template.docx";
string outFilename = "ChangeTextProperties.docx";
string outPdfFilename = "ChangeTextProperties.pdf";
// create DocxDocumentEditor that allows to edit file "ChangeTextProperties_template.docx"
using (Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor editor =
new Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor(templateFilename))
{
// get document body
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentElement documentBody = editor.Body;
// set text color
documentBody.FindText("COLOR").Substring(0, 2).SetTextProperties(CreateColorTextProperties(System.Drawing.Color.Red));
documentBody.FindText("COLOR").Substring(2, 1).SetTextProperties(CreateColorTextProperties(System.Drawing.Color.Green));
documentBody.FindText("COLOR").Substring(3, 2).SetTextProperties(CreateColorTextProperties(System.Drawing.Color.Blue));
// highlight text
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties highlightedTextProperties =
new Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties();
highlightedTextProperties.Highlight = Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextHighlightType.Green;
documentBody.FindText("highlighted text").SetTextProperties(highlightedTextProperties);
// set text "bold text" as bold text
documentBody.FindText("bold text").SetTextProperties(Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties.BoldText);
// set text "italic text" as italic text
documentBody.FindText("italic text").SetTextProperties(Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties.ItalicText);
// set text "underline text" as underline text
documentBody.FindText("underline text").SetTextProperties(Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties.UnderlineText);
// set text "strike text" as striked out text
documentBody.FindText("strike text").SetTextProperties(Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties.StrikeText);
// change font size
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties setTextSize =
new Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties();
setTextSize.FontSize = 16;
documentBody.FindText("text with size 16pt").Substring(0, 4).SetTextProperties(setTextSize);
// change text style
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties setTextStyle =
new Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties();
setTextStyle.Style = editor.Styles.FindByName("RedStyle");
documentBody.FindText("RedStyle").SetTextProperties(setTextStyle);
// save changed document to a DOCX file
editor.Save(outFilename);
// export changed document to a PDF document
editor.Export(outPdfFilename);
}
}
/// <summary>
/// Creates the color text properties.
/// </summary>
/// <param name="color">The color.</param>
private static Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties CreateColorTextProperties(System.Drawing.Color color)
{
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties result =
new Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties();
result.Color = color;
return result;
}
Public Shared Sub DocxChangeTextPropertiesExample()
Dim templateFilename As String = "ChangeTextProperties_template.docx"
Dim outFilename As String = "ChangeTextProperties.docx"
Dim outPdfFilename As String = "ChangeTextProperties.pdf"
' create DocxDocumentEditor that allows to edit file "ChangeTextProperties_template.docx"
Using editor As New Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor(templateFilename)
' get document body
Dim documentBody As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentElement = editor.Body
' set text color
documentBody.FindText("COLOR").Substring(0, 2).SetTextProperties(CreateColorTextProperties(System.Drawing.Color.Red))
documentBody.FindText("COLOR").Substring(2, 1).SetTextProperties(CreateColorTextProperties(System.Drawing.Color.Green))
documentBody.FindText("COLOR").Substring(3, 2).SetTextProperties(CreateColorTextProperties(System.Drawing.Color.Blue))
' highlight text
Dim highlightedTextProperties As New Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties()
highlightedTextProperties.Highlight = Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextHighlightType.Green
documentBody.FindText("highlighted text").SetTextProperties(highlightedTextProperties)
' set text "bold text" as bold text
documentBody.FindText("bold text").SetTextProperties(Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties.BoldText)
' set text "italic text" as italic text
documentBody.FindText("italic text").SetTextProperties(Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties.ItalicText)
' set text "underline text" as underline text
documentBody.FindText("underline text").SetTextProperties(Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties.UnderlineText)
' set text "strike text" as striked out text
documentBody.FindText("strike text").SetTextProperties(Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties.StrikeText)
' change font size
Dim setTextSize As New Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties()
setTextSize.FontSize = 16
documentBody.FindText("text with size 16pt").Substring(0, 4).SetTextProperties(setTextSize)
' change text style
Dim setTextStyle As New Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties()
setTextStyle.Style = editor.Styles.FindByName("RedStyle")
documentBody.FindText("RedStyle").SetTextProperties(setTextStyle)
' save changed document to a DOCX file
editor.Save(outFilename)
' export changed document to a PDF document
editor.Export(outPdfFilename)
End Using
End Sub
''' <summary>
''' Creates the color text properties.
''' </summary>
''' <param name="color">The color.</param>
Private Shared Function CreateColorTextProperties(color As System.Drawing.Color) As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties
Dim result As New Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextProperties()
result.Color = color
Return result
End Function
Класс OpenXmlDocumentTable
OpenXmlDocumentTable представляет таблицу DOCX или XLSX документа и позволяет:
Класс OpenXmlDocumentTableRow
OpenXmlDocumentTableRow представляет строку DOCX или XLSX таблицы и позволяет:
Класс OpenXmlDocumentTableCell
OpenXmlDocumentTableCell представляет ячейку DOCX или XLSX таблицы и позволяет:
Вот C#/VB.NET код, который демонстрирует, как заполнить таблицу данных (в примере используется документ-шаблон
CopyTableRow_template.docx
):
public static void DocxCopyTableRowExample()
{
string templateFilename = "CopyTableRow_template.docx";
string outFilename = "CopyTableRow.docx";
string outPdfFilename = "CopyTableRow.pdf";
// create DocxDocumentEditor that allows to edit file "CopyTableRow_template.docx"
using (Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor editor =
new Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor(templateFilename))
{
// get document body
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentElement documentBody = editor.Body;
// get the first table
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTable table = editor.Tables[0];
// get the second table that contains template row
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTableRow templateRow = table[1];
// create an array that contains colors
System.Drawing.Color[] colors = new System.Drawing.Color[] {
System.Drawing.Color.Red,
System.Drawing.Color.Green,
System.Drawing.Color.Blue,
System.Drawing.Color.Orange,
System.Drawing.Color.Yellow
};
// for each color
for (int i = 0; i < colors.Length; i++)
{
// insert copy of template row before template row
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTableRow rowCopy =
(Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTableRow)templateRow.InsertCopyBeforeSelf();
// set row data
rowCopy[0].Text = string.Format("Copy {0} ({1})", i, colors[i]);
rowCopy["[cell1]"] = string.Format("cell data {0}", i);
// set cell colors
rowCopy[1].SetFillColor(colors[i]);
rowCopy[2].SetFillColor(colors[i]);
// if color has odd index in colors array
if ((i % 2) == 1)
{
// set row height to 10mm
rowCopy.Height = Vintasoft.Imaging.Utils.UnitOfMeasureConverter.ConvertToPoints(10, Vintasoft.Imaging.UnitOfMeasure.Millimeters);
}
}
// remove template row
templateRow.Remove();
// save changed document to a DOCX file
editor.Save(outFilename);
// export changed document to a PDF document
editor.Export(outPdfFilename);
}
}
Public Shared Sub DocxCopyTableRowExample()
Dim templateFilename As String = "CopyTableRow_template.docx"
Dim outFilename As String = "CopyTableRow.docx"
Dim outPdfFilename As String = "CopyTableRow.pdf"
' create DocxDocumentEditor that allows to edit file "CopyTableRow_template.docx"
Using editor As New Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor(templateFilename)
' get document body
Dim documentBody As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentElement = editor.Body
' get the first table
Dim table As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTable = editor.Tables(0)
' get the second table that contains template row
Dim templateRow As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTableRow = table(1)
' create an array that contains colors
Dim colors As System.Drawing.Color() = New System.Drawing.Color() {System.Drawing.Color.Red, System.Drawing.Color.Green, System.Drawing.Color.Blue, System.Drawing.Color.Orange, System.Drawing.Color.Yellow}
' for each color
For i As Integer = 0 To colors.Length - 1
' insert copy of template row before template row
Dim rowCopy As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTableRow = DirectCast(templateRow.InsertCopyBeforeSelf(), Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTableRow)
' set row data
rowCopy(0).Text = String.Format("Copy {0} ({1})", i, colors(i))
rowCopy("[cell1]") = String.Format("cell data {0}", i)
' set cell colors
rowCopy(1).SetFillColor(colors(i))
rowCopy(2).SetFillColor(colors(i))
' if color has odd index in colors array
If (i Mod 2) = 1 Then
' set row height to 10mm
rowCopy.Height = Vintasoft.Imaging.Utils.UnitOfMeasureConverter.ConvertToPoints(10, Vintasoft.Imaging.UnitOfMeasure.Millimeters)
End If
Next
' remove template row
templateRow.Remove()
' save changed document to a DOCX file
editor.Save(outFilename)
' export changed document to a PDF document
editor.Export(outPdfFilename)
End Using
End Sub
Вот C#/VB.NET код, который демонстрирует, как установить границы таблицы как в шаблонной ячейки таблицы (в примере используется документ-шаблон
SetTableBorders_template.docx
):
public static void DocxSetTableBordersExample()
{
string templateFilename = "SetTableBorders_template.docx";
string outFilename = "SetTableBorders.docx";
string outPdfFilename = "SetTableBorders.pdf";
// create DocxDocumentEditor that allows to edit file "SetTableBorders_template.docx"
using (Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor editor =
new Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor(templateFilename))
{
// get cell border templates
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTable bordersTemplateTable =
editor.Tables[0];
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTableCell boldBorderTemplate =
bordersTemplateTable.FindCell("[bold]");
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTableCell colorBorderTemplate =
bordersTemplateTable.FindCell("[color]");
// remove border template table
bordersTemplateTable.Remove();
// get test table
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTable table = editor.Tables[0];
// set borders from template cells
table.FindRow("[bold_row]").SetBorder(boldBorderTemplate);
table.FindCell("[bold_cell]").SetBorder(boldBorderTemplate);
table.FindRow("[color_row]").SetBorder(colorBorderTemplate);
table.FindCell("[color_cell]").SetBorder(colorBorderTemplate);
// set outside border inside table
table.SetOutsideBorder(table.FindCell("[bold_first]"), table.FindCell("[bold_last]"), boldBorderTemplate);
// save changed document to a DOCX file
editor.Save(outFilename);
// export changed document to a PDF document
editor.Export(outPdfFilename);
}
}
Public Shared Sub DocxSetTableBordersExample()
Dim templateFilename As String = "SetTableBorders_template.docx"
Dim outFilename As String = "SetTableBorders.docx"
Dim outPdfFilename As String = "SetTableBorders.pdf"
' create DocxDocumentEditor that allows to edit file "SetTableBorders_template.docx"
Using editor As New Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor(templateFilename)
' get cell border templates
Dim bordersTemplateTable As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTable = editor.Tables(0)
Dim boldBorderTemplate As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTableCell = bordersTemplateTable.FindCell("[bold]")
Dim colorBorderTemplate As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTableCell = bordersTemplateTable.FindCell("[color]")
' remove border template table
bordersTemplateTable.Remove()
' get test table
Dim table As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentTable = editor.Tables(0)
' set borders from template cells
table.FindRow("[bold_row]").SetBorder(boldBorderTemplate)
table.FindCell("[bold_cell]").SetBorder(boldBorderTemplate)
table.FindRow("[color_row]").SetBorder(colorBorderTemplate)
table.FindCell("[color_cell]").SetBorder(colorBorderTemplate)
' set outside border inside table
table.SetOutsideBorder(table.FindCell("[bold_first]"), table.FindCell("[bold_last]"), boldBorderTemplate)
' save changed document to a DOCX file
editor.Save(outFilename)
' export changed document to a PDF document
editor.Export(outPdfFilename)
End Using
End Sub
Класс OpenXmlDocumentImage
OpenXmlDocumentImage представляет изображение DOCX или XLSX документа:
Вот C#/VB.NET код, который демонстрирует, как установить изображение штрих-кода в DOCX документе (в примере используется документ-шаблон
SetBarcodeImage_template.docx
):
public static void DocxSetBarcodeImageExample()
{
string templateFilename = "SetBarcodeImage_template.docx";
string outFilename = "SetBarcodeImage.docx";
string outPdfFilename = "SetBarcodeImage.pdf";
// create DocxDocumentEditor that allows to edit file "SetBarcodeImage_template.docx"
using (Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor editor =
new Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor(templateFilename))
{
// get document body
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentElement documentBody = editor.Body;
// find text content "Invoice number:"
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextContent textContent = documentBody.FindText("Invoice number:");
// get barcode value as text of next paragraph after "Invoice number:"
string barcodeValue = textContent.FindAfter<Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentParagraph>().Text;
barcodeValue = barcodeValue.TrimEnd('\n');
// create and setup barcode generator
Vintasoft.Barcode.BarcodeWriter barcodeGenerator = new Vintasoft.Barcode.BarcodeWriter();
barcodeGenerator.Settings.Barcode = Vintasoft.Barcode.BarcodeType.QR;
barcodeGenerator.Settings.SetWidth(200);
barcodeGenerator.Settings.Value = barcodeValue;
// generate barcode image
using (Vintasoft.Imaging.VintasoftImage barcodeImage =
new Vintasoft.Imaging.VintasoftImage(barcodeGenerator.GetBarcodeAsVintasoftBitmap(), true))
{
// crop barcode to rectangular image
barcodeImage.Crop(new System.Drawing.Rectangle(0, 0, barcodeImage.Width, barcodeImage.Width));
// set barcode image to DOCX image at index 0
editor.Images[0].SetImage(barcodeImage);
}
// save changed document to a DOCX file
editor.Save(outFilename);
// export changed document to a PDF document
editor.Export(outPdfFilename);
}
}
Public Shared Sub DocxSetBarcodeImageExample()
Dim templateFilename As String = "SetBarcodeImage_template.docx"
Dim outFilename As String = "SetBarcodeImage.docx"
Dim outPdfFilename As String = "SetBarcodeImage.pdf"
' create DocxDocumentEditor that allows to edit file "SetBarcodeImage_template.docx"
Using editor As New Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor(templateFilename)
' get document body
Dim documentBody As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentElement = editor.Body
' find text content "Invoice number:"
Dim textContent As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlTextContent = documentBody.FindText("Invoice number:")
' get barcode value as text of next paragraph after "Invoice number:"
Dim barcodeValue As String = textContent.FindAfter(Of Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentParagraph)().Text
barcodeValue = barcodeValue.TrimEnd(ControlChars.Lf)
' create and setup barcode generator
Dim barcodeGenerator As New Vintasoft.Barcode.BarcodeWriter()
barcodeGenerator.Settings.Barcode = Vintasoft.Barcode.BarcodeType.QR
barcodeGenerator.Settings.SetWidth(200)
barcodeGenerator.Settings.Value = barcodeValue
' generate barcode image
Using barcodeImage As New Vintasoft.Imaging.VintasoftImage(barcodeGenerator.GetBarcodeAsVintasoftBitmap(), True)
' crop barcode to rectangular image
barcodeImage.Crop(New System.Drawing.Rectangle(0, 0, barcodeImage.Width, barcodeImage.Width))
' set barcode image to DOCX image at index 0
editor.Images(0).SetImage(barcodeImage)
End Using
' save changed document to a DOCX file
editor.Save(outFilename)
' export changed document to a PDF document
editor.Export(outPdfFilename)
End Using
End Sub
Класс OpenXmlDocumentChart
OpenXmlDocumentChart представляет диаграмму DOCX или XLSX документа:
Вот C#/VB.NET код, который демонстрирует, как создать DOCX файл с диаграммой (в примере используется документ-шаблон
Chart.docx
):
/// <summary>
/// Creates the DOCX document with chart.
/// </summary>
/// <param name="resultFilePath">The result file path.</param>
public static void CreateDocxWithChart(string resultFilePath)
{
// path to a template DOCX document with chart
string templateDocDocumentPath = "Chart.docx";
// create DOCX document editor on template document with chart
using (Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor docxDocumentEditor =
new Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor(templateDocDocumentPath))
{
// get chart
Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentChart chart = docxDocumentEditor.Charts[0];
// change chart title
// find title
chart.Title = "Chart Title Example. " + System.DateTime.Now.ToShortDateString();
// change chart data
// create the chart data
double?[,] chartData = new double?[,] {
{ 55, 32, 23 },
{ 84, 48, 33 },
{ 72, 53, 86 },
{ 34, 82, 11 } };
// change the chart data
chart.ChartData.SetData(chartData);
// save changes
docxDocumentEditor.Save(resultFilePath);
}
}
''' <summary>
''' Creates the DOCX document with chart.
''' </summary>
''' <param name="resultFilePath">The result file path.</param>
Public Shared Sub CreateDocxWithChart(resultFilePath As String)
' path to a template DOCX document with chart
Dim templateDocDocumentPath As String = "Chart.docx"
' create DOCX document editor on template document with chart
Using docxDocumentEditor As New Vintasoft.Imaging.Office.OpenXml.Editor.Docx.DocxDocumentEditor(templateDocDocumentPath)
' get chart
Dim chart As Vintasoft.Imaging.Office.OpenXml.Editor.OpenXmlDocumentChart = docxDocumentEditor.Charts(0)
' change chart title
' find title
chart.Title = "Chart Title Example. " & System.DateTime.Now.ToShortDateString()
' change chart data
' create the chart data
Dim chartData As System.Nullable(Of Double)(,) = New System.Nullable(Of Double)(,) {{55, 32, 23}, {84, 48, 33}, {72, 53, 86}, {34, 82, 11}}
' change the chart data
chart.ChartData.SetData(chartData)
' save changes
docxDocumentEditor.Save(resultFilePath)
End Using
End Sub