Inserir uma tabela em um documento de processamento de texto
Este tópico mostra como utilizar as classes no SDK Open XML para o Office para inserir programaticamente uma tabela num documento de processamento de palavras.
Como obter um objeto WordprocessingDocument
Para abrir um documento existente, instanciar a WordprocessingDocument classe conforme mostrado na seguinte using
instrução. Na mesma instrução, abra o ficheiro de processamento de palavras no caminho de ficheiro especificado com o Open método , com o parâmetro Booleano definido como para true
ativar a edição do documento.
using (WordprocessingDocument doc = WordprocessingDocument.Open(fileName, true))
Com a v3.0.0+ o Close() método foi removido a favor de depender da instrução using.
Garante que o Dispose() método é chamado automaticamente quando a chaveta de fecho é atingida. O bloco que segue a instrução using estabelece um âmbito para o objeto que é criado ou nomeado na instrução using. Uma vez que a WordprocessingDocument classe no SDK Open XML guarda e fecha automaticamente o objeto como parte da respetiva IDisposable implementação e porque Dispose() é automaticamente chamada quando sai do bloco, não tem de chamar Save() explicitamente ou Dispose() desde que utilize uma using
instrução.
Estrutura de uma Tabela
A estrutura de documentos básica de um WordProcessingML
documento consiste nos document
elementos e body
, seguidos por um ou mais elementos de nível de bloco, como p
, que representa um parágrafo. Um parágrafo contém um ou mais r
elementos. O r significa executar, que é uma região de texto com um conjunto comum de propriedades, como formatação. Uma execução contém um ou mais t
elementos. O t
elemento contém um intervalo de texto. O documento pode conter uma tabela como neste exemplo. Uma tabela é um conjunto de parágrafos (e outros conteúdos ao nível do bloco) dispostos em linhas e colunas. As tabelas no WordprocessingML
são definidas através do tbl
elemento , que é análogo à etiqueta de tabela HTML. Considere uma tabela vazia de uma célula (ou seja, uma tabela com uma linha, uma coluna) e limites de 1 ponto em todos os lados. Esta tabela é representada pelo seguinte WordprocessingML
segmento de marcação.
<w:tbl>
<w:tblPr>
<w:tblW w:w="5000" w:type="pct"/>
<w:tblBorders>
<w:top w:val="single" w:sz="4" w:space="0" w:color="auto"/>
<w:left w:val="single" w:sz="4" w:space="0" w:color="auto"/>
<w:bottom w:val="single" w:sz="4" w:space="0" w:color="auto"/>
<w:right w:val="single" w:sz="4" w:space="0" w:color="auto"/>
</w:tblBorders>
</w:tblPr>
<w:tblGrid>
<w:gridCol w:w="10296"/>
</w:tblGrid>
<w:tr>
<w:tc>
<w:tcPr>
<w:tcW w:w="0" w:type="auto"/>
</w:tcPr>
<w:p/>
</w:tc>
</w:tr>
</w:tbl>
Esta tabela especifica propriedades ao nível da tabela de 100% da largura da página com o tblW
elemento , um conjunto de limites de tabela com o tblBorders
elemento , a grelha da tabela, que define um conjunto de arestas verticais partilhadas dentro da tabela com o tblGrid
elemento e uma única linha de tabela com o tr
elemento .
Como funciona o código de exemplo
No código de exemplo, depois de abrir o documento na using
instrução , crie um novo Table objeto. Em seguida, crie um TableProperties objeto e especifique as respetivas informações de limite.
A TableProperties classe contém um construtor TableProperties() sobrecarregado que utiliza uma params
matriz do tipo OpenXmlElement. O código utiliza este construtor para instanciar um TableProperties
objeto com BorderType objetos para cada limite, instanciando cada um BorderType
e especificando o respetivo valor através de inicializadores de objetos.
Depois de ser instanciado, acrescente o TableProperties
objeto à tabela.
// Create an empty table.
Table table = new Table();
// Create a TableProperties object and specify its border information.
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new BottomBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new LeftBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new RightBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideHorizontalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideVerticalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
}
)
);
// Append the TableProperties object to the empty table.
table.AppendChild<TableProperties>(tblProp);
O código cria uma linha de tabela. Esta secção do código utiliza extensivamente Append os métodos sobrecarregados, que classes derivadas de OpenXmlElement
herdar. Os Append
métodos fornecem uma forma de acrescentar um único elemento ou acrescentar uma parte de uma árvore XML ao final da lista de elementos subordinados num determinado elemento principal. Em seguida, o código cria um TableCell objeto, que representa uma célula de tabela individual, e especifica a propriedade de largura da célula da tabela com um TableCellProperties objeto e o conteúdo da célula ("Hello, Mundo!") com um Text objeto.
No esquema Open XML Wordprocessing, um elemento de parágrafo (<p\>
) contém elementos de execução (<r\>
) que, por sua vez, contêm elementos de texto (<t\>
). Para inserir texto numa célula de tabela com a API, tem de criar um Paragraph objeto que contenha um Run objeto que contenha um Text
objeto que contenha o texto que pretende inserir na célula.
Em seguida, acrescente o Paragraph
objeto ao TableCell
objeto . Esta ação cria a estrutura XML adequada para inserir texto numa célula. O TableCell
é, em seguida, anexado ao TableRow objeto.
// Create a row.
TableRow tr = new TableRow();
// Create a cell.
TableCell tc1 = new TableCell();
// Specify the width property of the table cell.
tc1.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
// Specify the table cell content.
tc1.Append(new Paragraph(new Run(new Text("some text"))));
// Append the table cell to the table row.
tr.Append(tc1);
Em seguida, o código cria uma segunda célula de tabela. A secção final do código cria outra célula de tabela com o construtor TableCell(String) sobrecarregado TableCell
que utiliza a OuterXml propriedade de um objeto existente TableCell
como o seu único argumento. Depois de criar a segunda célula da tabela, o código acrescenta o TableCell
ao TableRow
, acrescenta o TableRow
ao Table
e ao Table
Document objeto .
// Create a second table cell by copying the OuterXml value of the first table cell.
TableCell tc2 = new TableCell(tc1.OuterXml);
// Append the table cell to the table row.
tr.Append(tc2);
// Append the table row to the table.
table.Append(tr);
if (doc.MainDocumentPart is null || doc.MainDocumentPart.Document.Body is null)
{
throw new ArgumentNullException("MainDocumentPart and/or Body is null.");
}
// Append the table to the document.
doc.MainDocumentPart.Document.Body.Append(table);
Código de exemplo
O seguinte exemplo de código mostra como criar uma tabela, definir as respetivas propriedades, inserir texto numa célula na tabela, copiar uma célula e, em seguida, inserir a tabela num documento de processamento de palavras. Pode invocar o método CreateTable
com a seguinte chamada.
string filePath = args[0];
CreateTable(filePath);
Depois de executar o programa, inspecione o ficheiro para ver a tabela inserida.
A seguir está o código de exemplo completo em C# e em Visual Basic.
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
// Insert a table into a word processing document.
static void CreateTable(string fileName)
{
// Use the file name and path passed in as an argument
// to open an existing Word document.
using (WordprocessingDocument doc = WordprocessingDocument.Open(fileName, true))
{
// Create an empty table.
Table table = new Table();
// Create a TableProperties object and specify its border information.
TableProperties tblProp = new TableProperties(
new TableBorders(
new TopBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new BottomBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new LeftBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new RightBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideHorizontalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
},
new InsideVerticalBorder()
{
Val =
new EnumValue<BorderValues>(BorderValues.Dashed),
Size = 24
}
)
);
// Append the TableProperties object to the empty table.
table.AppendChild<TableProperties>(tblProp);
// Create a row.
TableRow tr = new TableRow();
// Create a cell.
TableCell tc1 = new TableCell();
// Specify the width property of the table cell.
tc1.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
// Specify the table cell content.
tc1.Append(new Paragraph(new Run(new Text("some text"))));
// Append the table cell to the table row.
tr.Append(tc1);
// Create a second table cell by copying the OuterXml value of the first table cell.
TableCell tc2 = new TableCell(tc1.OuterXml);
// Append the table cell to the table row.
tr.Append(tc2);
// Append the table row to the table.
table.Append(tr);
if (doc.MainDocumentPart is null || doc.MainDocumentPart.Document.Body is null)
{
throw new ArgumentNullException("MainDocumentPart and/or Body is null.");
}
// Append the table to the document.
doc.MainDocumentPart.Document.Body.Append(table);
}
}