Word создать таблицу программно

title description ms.date ms.topic dev_langs helpviewer_keywords author ms.author manager ms.technology ms.workload

How to: Programmatically create Word tables

Learn how to use the Add method of the Tables collection to add a table at the specified range in a Microsoft Word document.

02/02/2017

how-to

VB

CSharp

documents [Office development in Visual Studio], adding tables

tables [Office development in Visual Studio], adding to documents

John-Hart

johnhart

jmartens

office-development

office

How to: Programmatically create Word tables

[!INCLUDE Visual Studio]
The xref:Microsoft.Office.Interop.Word.Tables collection is a member of the xref:Microsoft.Office.Interop.Word.Document, xref:Microsoft.Office.Tools.Word.Document, xref:Microsoft.Office.Interop.Word.Selection, and xref:Microsoft.Office.Interop.Word.Range classes, which means that you can create a table in any of those contexts. You use the xref:Microsoft.Office.Interop.Word.Tables.Add%2A method of the xref:Microsoft.Office.Interop.Word.Tables collection to add a table at the specified range.

[!INCLUDEappliesto_wdalldocapp]

Create tables in document-level customizations

To add a table to a document

  • Use the xref:Microsoft.Office.Interop.Word.Tables.Add%2A method to add a table consisting of three rows and four columns at the beginning of the document.

    To use the following code example, run it from the ThisDocument class in your project.

    C#

    :::code language=»csharp» source=»../vsto/codesnippet/CSharp/Trin_VstcoreWordAutomationCS/ThisDocument.cs» id=»Snippet86″:::

    VB

    :::code language=»vb» source=»../vsto/codesnippet/VisualBasic/Trin_VstcoreWordAutomationVB/ThisDocument.vb» id=»Snippet86″:::

    When you create a table, it is automatically added to the xref:Microsoft.Office.Interop.Word.Tables collection of the xref:Microsoft.Office.Tools.Word.Document host item. You can then refer to the table by its item number by using the xref:Microsoft.Office.Interop.Word.Tables.Item%2A property, as shown in the following code.

To refer to a table by item number

  1. Use the xref:Microsoft.Office.Interop.Word.Tables.Item%2A property and supply the item number of the table that you want to refer to.

    To use the following code example, run it from the ThisDocument class in your project.

    C#

    :::code language=»csharp» source=»../vsto/codesnippet/CSharp/Trin_VstcoreWordAutomationCS/ThisDocument.cs» id=»Snippet87″:::

    VB

    :::code language=»vb» source=»../vsto/codesnippet/VisualBasic/Trin_VstcoreWordAutomationVB/ThisDocument.vb» id=»Snippet87″:::

    Each xref:Microsoft.Office.Interop.Word.Table object also has a xref:Microsoft.Office.Interop.Word.Table.Range%2A property that enables you to set formatting attributes.

To apply a style to a table

  1. Use the xref:Microsoft.Office.Interop.Word.Table.Style%2A property to apply one of the Word built-in styles to a table.

    To use the following code example, run it from the ThisDocument class in your project.

    C#

    :::code language=»csharp» source=»../vsto/codesnippet/CSharp/Trin_VstcoreWordAutomationCS/ThisDocument.cs» id=»Snippet88″:::

    VB

    :::code language=»vb» source=»../vsto/codesnippet/VisualBasic/Trin_VstcoreWordAutomationVB/ThisDocument.vb» id=»Snippet88″:::

Create tables in VSTO Add-ins

To add a table to a document

  • Use the xref:Microsoft.Office.Interop.Word.Tables.Add%2A method to add a table consisting of three rows and four columns at the beginning of the document.

    The following code example adds a table to the active document. To use this example, run it from the ThisAddIn class in your project.

    C#

    :::code language=»csharp» source=»../vsto/codesnippet/CSharp/Trin_VstcoreWordAutomationAddIn/ThisAddIn.cs» id=»Snippet86″:::

    VB

    :::code language=»vb» source=»../vsto/codesnippet/VisualBasic/Trin_VstcoreWordAutomationAddIn/ThisAddIn.vb» id=»Snippet86″:::

    When you create a table, it is automatically added to the xref:Microsoft.Office.Interop.Word.Tables collection of the xref:Microsoft.Office.Interop.Word.Document. You can then refer to the table by its item number by using the xref:Microsoft.Office.Interop.Word.Tables.Item%2A property, as shown in the following code.

To refer to a table by item number

  1. Use the xref:Microsoft.Office.Interop.Word.Tables.Item%2A property and supply the item number of the table that you want to refer to.

    The following code example uses the active document. To use this example, run it from the ThisAddIn class in your project.

    C#

    :::code language=»csharp» source=»../vsto/codesnippet/CSharp/Trin_VstcoreWordAutomationAddIn/ThisAddIn.cs» id=»Snippet87″:::

    VB

    :::code language=»vb» source=»../vsto/codesnippet/VisualBasic/Trin_VstcoreWordAutomationAddIn/ThisAddIn.vb» id=»Snippet87″:::

    Each xref:Microsoft.Office.Interop.Word.Table object also has a xref:Microsoft.Office.Interop.Word.Table.Range%2A property that enables you to set formatting attributes.

To apply a style to a table

  1. Use the xref:Microsoft.Office.Interop.Word.Table.Style%2A property to apply one of the Word built-in styles to a table.

    The following code example uses the active document. To use this example, run it from the ThisAddIn class in your project.

    C#

    :::code language=»csharp» source=»../vsto/codesnippet/CSharp/Trin_VstcoreWordAutomationAddIn/ThisAddIn.cs» id=»Snippet88″:::

    VB

    :::code language=»vb» source=»../vsto/codesnippet/VisualBasic/Trin_VstcoreWordAutomationAddIn/ThisAddIn.vb» id=»Snippet88″:::

See also

  • How to: Programmatically add text and formatting to cells in Word tables
  • How to: Programmatically add rows and columns to Word tables
  • How to: Programmatically populate Word tables with document properties
  • Optional parameters in Office solutions

Создание таблиц в документе Word из кода VBA Excel. Метод Tables.Add, его синтаксис и параметры. Объекты Table, Column, Row, Cell. Границы таблиц и стили.

Работа с Word из кода VBA Excel
Часть 4. Создание таблиц в документе Word
[Часть 1] [Часть 2] [Часть 3] [Часть 4] [Часть 5] [Часть 6]

Таблицы в VBA Word принадлежат коллекции Tables, которая предусмотрена для объектов Document, Selection и Range. Новая таблица создается с помощью метода Tables.Add.

Синтаксис метода Tables.Add

Expression.Add (Range, Rows, Columns, DefaultTableBehavior, AutoFitBehavior)

Expression – выражение, возвращающее коллекцию Tables.

Параметры метода Tables.Add

  • Range – диапазон, в котором будет создана таблица (обязательный параметр).
  • Rows – количество строк в создаваемой таблице (обязательный параметр).
  • Columns – количество столбцов в создаваемой таблице (обязательный параметр).
  • DefaultTableBehavior – включает и отключает автоподбор ширины ячеек в соответствии с их содержимым (необязательный параметр).
  • AutoFitBehavior – определяет правила автоподбора размера таблицы в документе Word (необязательный параметр).

Создание таблицы в документе

Создание таблицы из 3 строк и 4 столбцов в документе myDocument без содержимого и присвоение ссылки на нее переменной myTable:

With myDocument

Set myTable = .Tables.Add(.Range(Start:=0, End:=0), 3, 4)

End With

Создание таблицы из 5 строк и 4 столбцов в документе Word с содержимым:

With myDocument

myInt = .Range.Characters.Count 1

Set myTable = .Tables.Add(.Range(Start:=myInt, End:=myInt), 5, 4)

End With

Для указания точки вставки таблицы присваиваем числовой переменной количество символов в документе минус один. Вычитаем единицу, чтобы исключить из подсчета последний знак завершения абзаца (¶), так как точка вставки не может располагаться за ним.

Последний знак завершения абзаца всегда присутствует в документе Word, в том числе и в новом без содержимого, поэтому такой код подойдет и для пустого документа.

При создании, каждой новой таблице в документе присваивается индекс, по которому к ней можно обращаться:

myDocument.Tables(индекс)

Нумерация индексов начинается с единицы.

Отображение границ таблицы

Новая таблица в документе Word из кода VBA Excel создается без границ. Отобразить их можно несколькими способами:

Вариант 1
Присвоение таблице стиля, отображающего все границы:

myTable.Style = «Сетка таблицы»

Вариант 2
Отображение внешних и внутренних границ в таблице:

With myTable

.Borders.OutsideLineStyle = wdLineStyleSingle

.Borders.InsideLineStyle = wdLineStyleSingle

End With

Вариант 3
Отображение всех границ в таблице по отдельности:

With myTable

.Borders(wdBorderHorizontal) = True

.Borders(wdBorderVertical) = True

.Borders(wdBorderTop) = True

.Borders(wdBorderLeft) = True

.Borders(wdBorderRight) = True

.Borders(wdBorderBottom) = True

End With

Присвоение таблицам стилей

Вариант 1

myTable.Style = «Таблица простая 5»

Чтобы узнать название нужного стиля, в списке стилей конструктора таблиц наведите на него указатель мыши. Название отобразится в подсказке. Кроме того, можно записать макрос с присвоением таблице стиля и взять название из него.

Вариант 2

myTable.AutoFormat wdTableFormatClassic1

Выбирайте нужную константу с помощью листа подсказок свойств и методов – Auto List Members.

Обращение к ячейкам таблицы

Обращение к ячейкам второй таблицы myTable2 в документе myDocument по индексам строк и столбцов:

myTable2.Cell(nRow, nColumn)

myDocument.Tables(2).Cell(nRow, nColumn)

  • nRow – номер строки;
  • nColumn – номер столбца.

Обращение к ячейкам таблицы myTable в документе Word с помощью свойства Cell объектов Row и Column и запись в них текста:

myTable.Rows(2).Cells(2).Range = _

«Содержимое ячейки во 2 строке 2 столбца»

myTable.Columns(3).Cells(1).Range = _

«Содержимое ячейки в 1 строке 3 столбца»

В таблице myTable должно быть как минимум 2 строки и 3 столбца.

Примеры создания таблиц Word

Пример 1
Создание таблицы в новом документе Word со сплошными наружными границами и пунктирными внутри:

Sub Primer1()

Dim myWord As New Word.Application, _

myDocument As Word.Document, myTable As Word.Table

  Set myDocument = myWord.Documents.Add

  myWord.Visible = True

With myDocument

  Set myTable = .Tables.Add(.Range(0, 0), 5, 4)

End With

With myTable

  .Borders.OutsideLineStyle = wdLineStyleSingle

  .Borders.InsideLineStyle = wdLineStyleDot

End With

End Sub

В выражении myDocument.Range(Start:=0, End:=0) ключевые слова Start и End можно не указывать – myDocument.Range(0, 0).

Пример 2
Создание таблицы под ранее вставленным заголовком, заполнение ячеек таблицы и применение автосуммы:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

Sub Primer2()

On Error GoTo Instr

Dim myWord As New Word.Application, _

myDocument As Word.Document, _

myTable As Word.Table, myInt As Integer

  Set myDocument = myWord.Documents.Add

  myWord.Visible = True

With myDocument

‘Вставляем заголовок таблицы

  .Range.InsertAfter «Продажи фруктов в 2019 году» & vbCr

  myInt = .Range.Characters.Count 1

‘Присваиваем заголовку стиль

  .Range(0, myInt).Style = «Заголовок 1»

‘Создаем таблицу

  Set myTable = .Tables.Add(.Range(myInt, myInt), 4, 4)

End With

With myTable

‘Отображаем сетку таблицы

  .Borders.OutsideLineStyle = wdLineStyleSingle

  .Borders.InsideLineStyle = wdLineStyleSingle

‘Форматируем первую и четвертую строки

  .Rows(1).Range.Bold = True

  .Rows(4).Range.Bold = True

‘Заполняем первый столбец

  .Columns(1).Cells(1).Range = «Наименование»

  .Columns(1).Cells(2).Range = «1 квартал»

  .Columns(1).Cells(3).Range = «2 квартал»

  .Columns(1).Cells(4).Range = «Итого»

‘Заполняем второй столбец

  .Columns(2).Cells(1).Range = «Бананы»

  .Columns(2).Cells(2).Range = «550»

  .Columns(2).Cells(3).Range = «490»

  .Columns(2).Cells(4).AutoSum

‘Заполняем третий столбец

  .Columns(3).Cells(1).Range = «Лимоны»

  .Columns(3).Cells(2).Range = «280»

  .Columns(3).Cells(3).Range = «310»

  .Columns(3).Cells(4).AutoSum

‘Заполняем четвертый столбец

  .Columns(4).Cells(1).Range = «Яблоки»

  .Columns(4).Cells(2).Range = «630»

  .Columns(4).Cells(3).Range = «620»

  .Columns(4).Cells(4).AutoSum

End With

‘Освобождаем переменные

Set myDocument = Nothing

Set myWord = Nothing

‘Завершаем процедуру

Exit Sub

‘Обработка ошибок

Instr:

If Err.Description <> «» Then

  MsgBox «Произошла ошибка: « & Err.Description

End If

If Not myWord Is Nothing Then

  myWord.Quit

  Set myDocument = Nothing

  Set myWord = Nothing

End If

End Sub

Метод AutoSum суммирует значения в ячейках одного столбца над ячейкой с суммой. При использовании его для сложения значений ячеек в одной строке, результат может быть непредсказуемым.

Чтобы просуммировать значения в строке слева от ячейки с суммой, используйте метод Formula объекта Cell:

myTable.Cell(2, 4).Formula («=SUM(LEFT)»)

Другие значения метода Formula, применяемые для суммирования значений ячеек:

  • «=SUM(ABOVE)» – сумма значений над ячейкой (аналог метода AutoSum);
  • «=SUM(BELOW)» – сумма значений под ячейкой;
  • «=SUM(RIGHT)» – сумма значений справа от ячейки.


20.12.2010, 23:30. Показов 14898. Ответов 3


Студворк — интернет-сервис помощи студентам

создать с помощью программы таблицу и чтобы она открывалась в word/ ( консольное приложение)
Есть наметки, но как соединить не знаю.
Информация об объектах Table хранится в виде ссылок на таблицы документа в свойстве Tables. Набор ссылок Tables доступен из объектов Document, Selection и Range и даже из объекта Word.Table. Это значит, что и создавать таблицы можно с использованием любого из этих объектов (в любом — применительно к таблицам). Для создания таблиц используется метод Add:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Add(
Word.Range Range, //Объект Range - место формирования таблицы
int NumRows,      //Число строк
int NumColumns,   //Число столбцов
ref object DefaultTableBehavior,//Определяет, изменяет ли Word 
                                //автоматически размеры ячеек в 
                                //таблицах, чтобы они  соответствовали 
                                //содержанию  ячеек. Может быть 
                                //одна из Word.WdDefaultTableBehavior 
                                //констант: wdWord8TableBehavior (нет) 
                                //или wdWord9TableBehavior (да). 
                                //По умолчанию - wdWord8TableBehavior. 
ref object AutoFitBehavior      //Автоподбор ширины столбцов
                                //одна из следующих Word.WdAutoFitBehavior
                                //констант: wdAutoFitContent - по 
                                //содержимому, wdAutoFitFixed -
                                //фиксированная или wdAutoFitWindow
                                //по ширине окна. Если DefaultTableBehavior
                                //установлен в wdWord8TableBehavior, 
                                //этот параметр игнорируется.
)

Пример создания таблицы:

C#
1
2
3
4
5
6
7
8
9
10
//Таблицу вставляем в начало документа
Object start = 0;
Object end = 0;
Word.Range wordrange = worddocument.Range(ref start, ref end);
Object defaultTableBehavior = 
   Word.WdDefaultTableBehavior.wdWord9TableBehavior;
Object autoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitWindow;
//Добавляем таблицу и получаем объект wordtable 
Word.Table wordtable = worddocument.Tables.Add(wordrange, 5, 5, 
                  ref defaultTableBehavior, ref autoFitBehavior);

После того как таблица добавлена в документ, объект, соответствующий добавленной таблице можно получить по ее номеру в порядке добавления:

C#
1
Word.Table wordtable = worddocument.Tables[1];

После того как мы добавили таблицу и получили объект Word.Table мы можем изменить стиль таблицы, например:

C#
1
2
3
4
5
6
7
8
Object style = "Классическая таблица 1";
wordtable.set_Style(ref style);
//Далее можно добавлять выделение первых
//и последних строк и столбцов
wordtable.ApplyStyleFirstColumn=true;
wordtable.ApplyStyleHeadingRows=true;
wordtable.ApplyStyleLastRow=false;
wordtable.ApplyStyleLastColumn=false;

Пример создания двух таблиц (Рис.8.). В примере не только показано как можно создать таблицу, но и как разместить ее в пределах документа Word. Пример, как и ранее, выполняется при открытии чистого документа C:a.doc, и, поэтому, здесь опускается часть кода, приводимая выше по открытию документа:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
case 1:
 
.......... 
 
 //Вставляем в документ 4 параграфа
 object oMissing = System.Reflection.Missing.Value;
 worddocument.Paragraphs.Add(ref oMissing);
 worddocument.Paragraphs.Add(ref oMissing);
 worddocument.Paragraphs.Add(ref oMissing);
 worddocument.Paragraphs.Add(ref oMissing);
 //Переходим к первому добавленному параграфу
 wordparagraph=worddocument.Paragraphs[2];
 Word.Range wordrange=wordparagraph.Range;
 //Добавляем таблицу в начало второго параграфа
 Object defaultTableBehavior = 
  Word.WdDefaultTableBehavior.wdWord9TableBehavior;
 Object autoFitBehavior = 
  Word.WdAutoFitBehavior.wdAutoFitWindow;
 Word.Table wordtable1 = worddocument.Tables.Add(wordrange, 5, 5, 
   ref defaultTableBehavior,ref autoFitBehavior);
 //Сдвигаемся вниз в конец документа
 object unit; 
 object extend; 
 unit = Word.WdUnits.wdStory; 
 extend = Word.WdMovementType.wdMove; 
 wordapp.Selection.EndKey(ref unit, ref extend); 
 //Вставляем таблицу по месту курсора
 Word.Table wordtable2 = worddocument.Tables.Add(
   wordapp.Selection.Range, 4, 4, ref defaultTableBehavior,
 ref autoFitBehavior);
 //Меняем стили созданных таблиц
 Object style = "Классическая таблица 1";
 wordtable1.set_Style(ref style);
 style = "Сетка таблицы 3";
 Object applystyle = true;
 wordtable2.set_Style(ref style);
 wordtable2.ApplyStyleFirstColumn=true;
 wordtable2.ApplyStyleHeadingRows=true;
 wordtable2.ApplyStyleLastRow=false;
 wordtable2.ApplyStyleLastColumn=false;
break;



1



  • Download OpenXML_Word_Exe.zip
  • Download source

Introduction

Welcome back again in OpenXML world, where you can create a word table with the help of C# and OpenXML.

Here the magic is,  No need to install word on your machine, no Interop object required. Lets see how to drive it

Background

I have given brief explanation about ‘What is Open XML‘ in my previous article, if you are new to OpenXML then check out this link

http://www.codeproject.com/Tips/994905/Edit-Word-Documents-using-OpenXML-and-Csharp-Witho

OpenXML table structure

According to people, OpenXML is legthy and complex but if you understand it’s structure then it is really a cup of tea. So lets start with table structure first.

Things we need before going to openXML

Image 1   Image 2

Getting started with OpenXML Table

A table consists of rows and cells and is structured much like an HTML table. It is defined with the <w:tbl> element. Basic table structure can be defined as

<w:tbl>
    <w:tblpr>.....</w:tblpr>
    <w:tblgrid>....</w:tblgrid>
    <w:tr>....</w:tr>
</w:tbl>

In above structure we can see, Table has three main tag.

1. w:tblpr : Specifies the table-wide properties for the table. These properties can be overridden by individual table level

2. w:tblgrid : Specifies the columns for the table

3. w:tr : Specifies a table row

Let see them one by one in detail

1. w:tblpr :

This Specifies the table-wide properties for the table, Each property is a child element of <tblPr> , and they affect all rows and cells in the table, but the style can be overridden by each individual row, column or cell.

The most commonly used properties are shown below

Property Name Description
w:jc Represent table alignment.
w:shd Represent table shading.
w:Borders Represent table borders.
w:Caption Represent table Caption.
w:CellMar Represent table cell margins.
w:tblCellSpacing Represent table spacing.
w:tblLayout Represent table layout.
w:tblLook Represent table conditional formatting.

see below tag snippet

<w:tblPr>
	<w:tblStyle w:val="TestTableStyle"/>
	<w:jc w:val="center"/>
</w:tblPr>

2. w:tblgrid

The columns of a table are defined by the <w:tblGrid> element it contains attribute as <w:gridCol> which is the size of each columns, if the table has 4 columns then w:tblgrid has 4 w:gridCol tags

see below tag snippet

<w:tblGrid>
	<w:gridCol w:w="2800"/>
	<w:gridCol w:w="2600"/>
	<w:gridCol w:w="2800"/>
<w:tblGrid>

3.w:tr

This is the row defination tag, this is the core element of table. it has following subset

Property Name Description
w:trPr Represent row level properties, but can be overridden by individual cell
w:tblPrEx Represent table properties for the row,  These properties are typically used for legacy documents, as well as in cases where two independent tables are merged
w:tc Represent individual table cell.

see below tag snippet

<w:tr>
    <w:trPr>.....</w:trPr>
    <w:tblPrEx>....</w:tblPrEx>
    <w:tc>....</w:tc>
</w:tr>

Now we will see w:tr properties in depth.

3.1 w:trPr

This element represent row level properties, Each property is a child element of <trPr> , and they affect all cells in the row. Mostly used properties are as below

Property Name Description
w:cantSplit it prevents the contents of the row from breaking across multiple pages by moving the start of the row to the start of a new page, it help the row to start on next page
w:hidden Help to hide the entire row
w:jc Specifies the alignment of the row
w:tblCellSpacing Specifies the cell spacing, it is same like HTML table attribute
w:tblHeader Specifies the current row should be repeated as header of each table on new page
w:trHeight Represent the height of the row, if optional then height will be adjusted automatically

3.2 w:trPrEx

As described exceptional properties of the table, with the help of this property we can show any row with specific exception. w:trPrEx has almost same properties like <w:trPr>, some new properties are as below

Property Name Description
w:shd Specifies the background color, it is optional property, it has different attribute like color, fill, val.
w:tblBorders Specifies row borders
w:tblCellMar Specifies the margin of the cell, this is basically cell properties of exceptional row (we will see this property thoroughly in cell section)
w:tblInd Before leading edge of the row it adds indentation to the row,
w:tblLayout Specifies the inbuilt table layout
w:tblLook Specifies the inbuilt table layout specified by word application 

see below tag snippet

<w:tr>
   <w:tblPrEx>
	<w:tblBorders>
		<w:top w:val="single" w:sz="12" w:space="0" w:color="FF0000" />
		<w:start w:val="single" w:sz="24" w:space="0" w:color="00FF00" />
		<w:bottom w:val="single" w:sz="12" w:space="0" w:color="0000FF" />
		<w:end w:val="single" w:sz="24" w:space="0" w:color="000000" />
		<w:insideH w:val="single" w:sz="24" w:space="0" w:color="FFFF00" />
		<w:insideV w:val="single" w:sz="24" w:space="0" w:color="FF00FF" />
	</w:tblBorders>
   </w:tblPrEx>
</w:tr>

3.3 w:tc

This tag specifies data for individual table cell, these tags are nested under table row tags. The core elements of w:tc are as follows

Property Name Description
w:p Specifies the paragraph of each cell
w:tbl Specifies table as content of the cell
w:tcPr Specifies the properties to be applied to the current cell.

see below snippet

<w:tc>
   <w:tcPr>
	<w:tcW w:w="2600" w:type="dxa"/>
   </w:tcPr>
   <w:p>
	<w:r>
      	    <w:t>cell content</w:t>
	</w:r>
   </w:p>
</w:tc>

above markup snippet contains table cell, in which paragraph (<w:p>), Run (<w:p>), Text (<w:r>) are the child element of the cell.

3.3.1 w:p

Paragraph is the main part of the cell, The paragraph can contain rich formatting properties for the paragraph, Paragraphs may also contain bookmarks, hyperlinks, fields, comments, etc. The core element of paragraph is properties (<w:pPr>) and run (<w:r>

Both paragraph properties and run has their own properties like paragraph frames, indentation, alignment, numbering, border, paragraph style, shading and tabs.

see below markup

<w:p>
   <w:pPr>
	<w:pStyle> w:val="TestWeb"/>
	<w:spacing w:before="20" w:after="20"/>
   </w:pPr>
   <w:r>
	<w:t>This is cell content</w:t>
   </w:r>
</w:p>

3.3.2 w:tcPr

tcPr represent cellwise properties, this properties are used to decorate cell. Row and column wise properties can be overridden in this section 

Property Name Description
w:gridSpan Specifies the spanning cell across rows
w:hideMark Specifies hide end of the table cell mark
w:noWrap Specifies the prevent text from wrapping, it is boolean property
w:tcBorders Specifies table cell border
w:tcFitText Specifies text within the cell can be extend to the width of the cell, this is the boolean property
w:tcMar Specifies table cell margins
w:tcW Specifies table cell width
w:vAlign Specifies table cell vertical alignments
w:vMerge This property indicates if the cell is part of merged group cell, it has two possible values continue and restart

3.3.1.1 w:r

Run defines a text properties. Most commonly run contains only text but it may have content as symbols, tabs, hyphens, carriage returns, drawings, breaks, and footnote references

see below properties of Run element

Property Name Description
w:br Specifies a break e.g. <w:br/>
w:cr Specifies a carriage return
w:drawing Specifies the layout of the DrawingML object within the document
w:noBreakHypen Specifies the non breaking hypen.
w:rPr Specifies the properties of the run like
w:softHypen Specifies the inbuilt table layout specified by word application 
w:sym Specifies a special character or symbol
w:t Spcifies the actual text which will display in cell, This is very important and core element of Table markup, this element hold actual text contents.
w:tab Specifies the TAB character

see below markup snippet

<w:r>
   <w:rPr>
	<w:b/>
	<w:i/>
    </w:rPr>
    <w:t>This is sample text</w:t>
</w:r>

3.3.1.1.1 w:rPr

 This element contains different properties of the Run, which is then applies to actual text exist in  <w:t> section

here are the most commonly used properties of the run

Property Name Description
w:b Display text in bold, exist in Text element e.g. <w:b />
w:i Display text in Italics, exist in Text element e.g. <w:i />  
w:caps Display text in small or upper caps depend upon ‘val’ attributes e.g. <w:caps w:val=»true» />
w:color Display text in specified color, it accept color code for color e.g. <w:color w:val=»FF1244″ />
w:dstrike Display text in Strike through format e.g. <w:dstrike w:val=»true»/>
w:emboss Display text in emboss style e.g. <w:emboss w:val=»true» />
w:imprint Display text in imprint style e.g. <w:imprint w:val=»true»/>
w:outline Display text in outline style e.g. <outline w:val=»true»/>
w:rStyle Display character style depend upon style ID (Here style is inbuilt)
w:shadow Display text has shadow for each character <w:shadow w:val=»true»/>
w:smallCaps Display text in small capital letter, The difference between caps and smallCaps is, caps make the text size larger and convert text to capital where as smallCaps convert text to capital but does not increase the font e.g. <w:smallCaps w:val=»true»/>  
w:sz Display the text in specified size, e.g. <w:sz w:val=»14″/> .
w:u Display the text in underline, e.g. <w:u w:val=»double»/>
w:vanish Text in this element will be hidden from display, e.g. <vanish/>
w:vertAlign Display text in Super or subscript e.g. <vertAlign w:val=»superscript | baseline | subscript  «/>

So here is the raw hierarchy structure of OpenXML table format

Image 3

Go with Markup and code

Now with the above all markup’s we can create a table in word (DOCX) file, here i have develope a small application that will put a nice table in word file

first create table properties, see below xml markup’s (We have apply inbuilt table style and look as Accept4)

<w:tblPr>
	<w:tblStyle w:val="LightGrid-Accent4" />
	<w:tblW w:w="0" w:type="auto" />
	<w:tblLook w:val="04A0" />
</w:tblPr>

then we will add columns in table, see below xml markup’s (We have take 3 columns)

<w:tblGrid> 
	<w:gridCol w:w="2394" />
	<w:gridCol w:w="2394" /> 
	<w:gridCol w:w="2394" /> 
</w:tblGrid> 

Now we will add rows in it with text to be display. (We have added 1 row with 3 cell here)

<w:tr w:rsidR="004D1DA5" w:rsidTr="004D1DA5"> 
	<w:trPr> 
		<w:cnfStyle w:val="100000000000" /> 
	</w:trPr> 
	<w:tc> 
		<w:tcPr> 
			<w:cnfStyle w:val="001000000000" /> 
			<w:tcW w:w="2394" w:type="dxa" /> 
			<w:hideMark /> 
		</w:tcPr> 
		<w:p w:rsidR="004D1DA5" w:rsidRDefault="004D1DA5"> 
			<w:pPr> 
				<w:jc w:val="center" /> 
			</w:pPr> 
			<w:r> 
				<w:t>No</w:t> 
			</w:r> 
		</w:p> 
	</w:tc> 
	<w:tc> 
		<w:tcPr> 
			<w:tcW w:w="2394" w:type="dxa" /> 
			<w:hideMark /> 
		</w:tcPr> 
		<w:p w:rsidR="004D1DA5" w:rsidRDefault="004D1DA5"> 
			<w:pPr> 
				<w:jc w:val="center" /> 
				<w:cnfStyle w:val="100000000000" /> 
			</w:pPr> 
			<w:r> 
				<w:t>Name</w:t> 
			</w:r> 
		</w:p> 
	</w:tc> 
	<w:tc> 
		<w:tcPr> 
			<w:tcW w:w="2394" w:type="dxa" /> 
			<w:hideMark /> 
		</w:tcPr> 
		<w:p w:rsidR="004D1DA5" w:rsidRDefault="004D1DA5"> 
			<w:pPr> 
				<w:jc w:val="center" /> 
				<w:cnfStyle w:val="100000000000" /> 
			</w:pPr> 
			<w:r> 
				<w:t>Sex</w:t> 
			</w:r> 
		</w:p> 
	</w:tc> 
</w:tr> 

Here is code to create Markup

# Create table object and add table properties

Table table1 = new Table();


TableProperties tableProperties1 = new TableProperties();
TableStyle tableStyle1 = new TableStyle() { Val = "LightGrid-Accent4" };
TableWidth tableWidth1 = new TableWidth() { Width = "0", Type = TableWidthUnitValues.Auto };
TableLook tableLook1 = new TableLook() { Val = "04A0" };


tableProperties1.Append(tableStyle1);
tableProperties1.Append(tableWidth1);
tableProperties1.Append(tableLook1);

# define table columns and add them in table

TableGrid tableGrid1 = new TableGrid();
GridColumn gridColumn1 = new GridColumn() { Width = "2394" };
GridColumn gridColumn2 = new GridColumn() { Width = "2394" };
GridColumn gridColumn3 = new GridColumn() { Width = "2394" };


tableGrid1.Append(gridColumn1);
tableGrid1.Append(gridColumn2);
tableGrid1.Append(gridColumn3);

# Define new cell object with its associated paragraph, Run, Text object and their properties respectively.

TableRow tableRow1 = new TableRow(){RsidTableRowAddition="004D1DA5",RsidTableRowProperties="004D1DA5"};


TableRowProperties tableRowProperties1 = new TableRowProperties();
ConditionalFormatStyle conditionalFormatStyle1 = new ConditionalFormatStyle(){Val="100000000000"};
tableRowProperties1.Append(conditionalFormatStyle1);


TableCell tableCell1 = new TableCell();
TableCellProperties tableCellProperties1 = new TableCellProperties();
ConditionalFormatStyle conditionalFormatStyle2 = new ConditionalFormatStyle(){Val="001000000000"};
TableCellWidth tableCellWidth1 = new TableCellWidth(){Width="2394",Type=TableWidthUnitValues.Dxa};
HideMark hideMark1 = new HideMark();
tableCellProperties1.Append(conditionalFormatStyle2);
tableCellProperties1.Append(tableCellWidth1);
tableCellProperties1.Append(hideMark1);


Paragraph paragraph1 = new Paragraph(){RsidParagraphAddition="004D1DA5",RsidRunAdditionDefault="004D1DA5"};
ParagraphProperties paragraphProperties1 = new ParagraphProperties();
Justification justification1 = new Justification() { Val = JustificationValues.Center };
paragraphProperties1.Append(justification1);


Run run1 = new Run();
Text text1 = new Text();


text1.Text = "No";


run1.Append(text1);


paragraph1.Append(paragraphProperties1);
paragraph1.Append(run1);


tableCell1.Append(tableCellProperties1);
tableCell1.Append(paragraph1);

Yes, we are done with our code now try to test it.

Summing Up

OpenXML is  is an open, international, ECMA-376, Second Edition and ISO/IEC 29500 standard, They are based on technologies like XML and ZIP. You can improve your application performance with the help of OpenXML, Developer can interact with DOCX file without opening it. With the help of openXML you can perform complex operations with just a few lines of code.

In this article we have seen how to draw a word table using OpenXML and C#

Till more to happen and learn, we will see more good samples in coming versions of this article.

Suggestions and Queries are always welcome.

Thanks

koolprasad2003

Одно дело, когда заранее известно количество строк в таблице. И решение, соответственно, тоже простое: создать в шаблоне таблицу и заполнить переменные программно.
Но вот совсем другой подход, когда количество строк или колонок неизвестно.
В этом примере продемонстрировано, как можно создать табличную часть в документе Word.
Выбор, какой из перечисленных далее методов использовать, за Вами.

Одно дело, когда заранее известно количество строк в таблице. И решение, соответственно, тоже простое: создать в шаблоне таблицу и заполнить переменные программно. Ссылка на данный пример //infostart.ru/public/18940/

Но вот совсем другой подход, когда количество строк или колонок неизвестно.

История «Как я к этому пришел»

Появилась необходимость распечатывать договора по каждому контрагенту, а как известно договор может быть 1 или несколько.

Тогда, еще в 2006 году вопрос решился 5 шаблонами, в табличных частях которых было от 1 до 5 строк (ограничились 5 договорами). Вопрос решился и забылся. Но вот вопрос стал актуален по причине печати нового договора, в котором задействована номенклатура, а количество строк ведь может переваливать добрую сотню наименований. И следовательно  — выход в создании динамической таблицы в шаблоне Word, который и описан двумя самыми простыми способами.

Есть 2 подхода к созданию таблицы.

1) Вам нужна таблица с равной шириной колонок, так сказать созданная автоматически.

2) У вас есть шаблон таблицы (только шапка и 1 строка).

Код создания таблицы с автоформатом.

Процедура СоздатьПример1(Кнопка)
НовоеНапоминание = ПолучитьМакет("Пример1");

Массив = Новый Массив(5);//сделаем таблицу из 5 строк + шапка

MsWord = НовоеНапоминание.Получить();


//макет является ActiveDocwment с загруженым в него Word-файлом
Попытка
//Вставление таблицы с 10 строки
MsWord.Application.Visible = 0;
Word = MsWord.Application;
Док=Word.Documents(1);
Док.Activate();

//подготовка таблицы:
//Вариант №1 Самый простой
Word.Selection.MoveDown(,10); //10 строка - первая строка таблицы
//Конец Варианта №1

//Вариант №2
Word.Bookmarks("ff").Select(); //Где ff - это набор любых символов, вплоть до непечатаемых;)
//Конец Варианта №2

Табл= Word.Selection.Range;
//Формируем заголовок:
Табл.InsertAfter("Сумма*Валюта*Назначение*Дата долга*Вид документа*Номер документа* *Дата оплаты");
Табл.InsertParagraphAfter();
//сама таблица
Для й = 1 по Массив.Количество() Цикл
Табл.InsertAfter(массЗнчСтрокиТЧ[0]+"*"+массЗнчСтрокиТЧ[1]+"*"+массЗнчСтрокиТЧ[2]+"*"+массЗнчСтрокиТЧ[3]+"*"+ массЗнчСтрокиТЧ[4]+ "*"+массЗнчСтрокиТЧ[5]+ "*"+массЗнчСтрокиТЧ[6]+ "*"+массЗнчСтрокиТЧ[7]);
Табл.InsertParagraphAfter();
КонецЦикла;

Табл.ConvertToTable("*");

//Происходит конвертация строки в таблицу

//не нравятся звездочки - используйте другой символ
Док.Tables(1).AutoFormat(1);

ПечатныйНомер = "-"+Формат(ТекущаяДата(),"ДФ=yyyy.MM.dd")+"-"+Формат(ДатаОтчета,"ДФ=yyyy.MM.dd");
Файл = КаталогВременныхФайлов() + "" + ПечатныйНомер + ".doc";

Док.SaveAs(Файл);
Док.Close(0);

//МассивДокументов.Добавить(Файл);  //добавлял в массив путь к файлу и после всех манипуляций открывал каждый файл
ЗапуститьПриложение("""" + Файл + """");

Исключение
Сообщить(ОписаниеОшибки());
Word.Quit();
КонецПопытки;

КонецПроцедуры

Код создания таблицы с наследуемым форматом.

Процедура СоздатьПример2(Кнопка)
НовоеНапоминание = ПолучитьМакет("Пример2");

Массив = Новый Массив(5);//добавим 4 строки

MsWord = НовоеНапоминание.Получить();
//макет является ActiveDocwment с загруженым в него Word-файлом
Попытка

MsWord.Application.Visible = 0;
Word = MsWord.Application;
Док=Word.Documents(1);
Док.Activate();


Если Массив.Количество()>1 Тогда
//Переместиться вниз на 10 строк от начала документа
Word.Selection.MoveDown(,10); //10 строка - первая строка таблицы
//назад на 1 символ (окончание строки таблицы)
Word.Selection.MoveLeft(,1);
//кво документов которые необходимо забить в табличную часть
Word.Selection.InsertRows(Массив.Количество()-1);

Word.Selection.MoveLeft(,1);
Для й = 11 по Массив.Количество()+9 Цикл
ЗаполнитьСтрокуТЧ(0,Word);
Word.Selection.MoveRight(,1);
КонецЦикла;
КонецЕсли;

ПечатныйНомер = "-"+Формат(ТекущаяДата(),"ДФ=yyyy.MM.dd")+"-"+Формат(ДатаОтчета,"ДФ=yyyy.MM.dd");

//Таблицу заполнять не буду, только шапку

Замена = Док.Content.Find;
Замена.Execute("", Ложь, Истина, Ложь, , , Истина, , Ложь, "ООО 'Пупкин inc.'");

Замена = Док.Content.Find;
Замена.Execute("", Ложь, Истина, Ложь, , , Истина, , Ложь, Формат(ТекущаяДата(),"Л=uk; ДЛФ=D"));

Замена = Док.Content.Find;
Замена.Execute("", Ложь, Истина, Ложь, , , Истина, , Ложь, ПечатныйНомер );

Файл = КаталогВременныхФайлов() + "" + ПечатныйНомер + ".doc";

Док.SaveAs(Файл);
Док.Close(0);

//МассивДокументов.Добавить(Файл);  //добавлял в массив путь к файлу и после всех манипуляций открывал каждый файл
ЗапуститьПриложение("""" + Файл + """");
Исключение
Сообщить(ОписаниеОшибки());
Word.Quit();
КонецПопытки;

КонецПроцедуры

Процедура ЗаполнитьСтрокуТЧ(знчЭл,Word)

Если знчЭл массЗнчСтрокиТЧ.Количество()-1 Тогда
текЭлем = массЗнчСтрокиТЧ[знчЭл];
Rng = Word.Selection.Range;
Rng.InsertAfter(текЭлем);
ДлинаЗнч = СтрДлина(текЭлем)+1;

Word.Selection.MoveRight(,ДлинаЗнч);

Если знчЭл < массЗнчСтрокиТЧ.Количество()-1 Тогда
знчЭл = знчЭл + 1;
ЗаполнитьСтрокуТЧ(знчЭл,Word);
КонецЕсли;
КонецЕсли;

КонецПроцедуры

Понравилась статья? Поделить с друзьями:
  • Word создать стиль с многоуровневым списком
  • Word создать стиль нумерованного списка
  • Word создать стиль нумерации
  • Word создать стиль для оглавления
  • Word создать стиль для всех документов