Применяйте стиль стола

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

Aspose.Words Поддерживает применение стиля стола к столу, а также свойства чтения любого стиля стола. Стили стола сохраняются при загрузке и экономии следующими способами:

  • Стили таблиц в форматах DOCX и WordML сохраняются при загрузке и сохранении этих форматов
  • Стили таблиц сохраняются при загрузке и сохранении в формате DOC (но не в любом другом формате)
  • При экспорте в другие форматы, рендеринге или печати стили таблиц расширяются до прямого форматирования в таблице, поэтому все форматирование сохраняется

Создайте стиль стола

Пользователь может создать новый стиль и добавить его в коллекцию стилей. The Add Метод используется для создания нового стиля стола.

Следующий пример кода показывает, как создать новый пользовательский определенный стиль таблицы:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.StartTable();
builder.InsertCell();
builder.Write("Name");
builder.InsertCell();
builder.Write("Value");
builder.EndRow();
builder.InsertCell();
builder.InsertCell();
builder.EndTable();
TableStyle tableStyle = (TableStyle) doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.Borders.LineStyle = LineStyle.Double;
tableStyle.Borders.LineWidth = 1;
tableStyle.LeftPadding = 18;
tableStyle.RightPadding = 18;
tableStyle.TopPadding = 12;
tableStyle.BottomPadding = 12;
table.Style = tableStyle;
doc.Save(ArtifactsDir + "WorkingWithTableStylesAndFormatting.CreateTableStyle.docx");

Копирование существующего стиля стола

При необходимости вы можете скопировать стиль таблицы, который уже существует в определенном документе, в свою коллекцию стилей. AddCopy метод.

Важно знать, что с этим копированием также копируются связанные стили.

Следующий пример кода показывает, как импортировать стиль из одного документа в другой:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document srcDoc = new Document();
// Create a custom style for the source document.
Style srcStyle = srcDoc.Styles.Add(StyleType.Paragraph, "MyStyle");
srcStyle.Font.Color = Color.Red;
// Import the source document's custom style into the destination document.
Document dstDoc = new Document();
Style newStyle = dstDoc.Styles.AddCopy(srcStyle);
// The imported style has an appearance identical to its source style.
Assert.AreEqual("MyStyle", newStyle.Name);
Assert.AreEqual(Color.Red.ToArgb(), newStyle.Font.Color.ToArgb());

Применяйте существующий стиль стола

Aspose.Words обеспечивает TableStyle унаследованной от Style класс. TableStyle облегчает пользователю применение различных вариантов стиля, таких как затенение, набивка, углубление, CellSpacing и Font, и т.д.

Кроме того, Aspose.Words обеспечивает StyleCollection Класс и некоторые свойства Table класс, чтобы определить, с каким стилем стола мы будем работать: Style, StyleIdentifier, StyleName, и StyleOptions.

Aspose.Words также предоставляет ConditionalStyle класс, который представляет собой специальное форматирование, применяемое к некоторой области таблицы с назначенным стилем таблицы, и ConditionalStyleCollection Представляет собой коллекцию ConditionalStyle объекты. Эта коллекция содержит постоянный набор элементов, представляющих один элемент для каждого значения ConditionalStyleType Тип перечисления. The ConditionalStyleType Перечисление определяет все возможные области таблицы, в которых условное форматирование может быть определено в стиле таблицы.

В этом случае условное форматирование может быть определено для всей возможной области таблицы, определенной по типу перечисления ConditionalStyleType.

Следующий пример кода показывает, как определить условное форматирование для строки заголовка таблицы:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.StartTable();
builder.InsertCell();
builder.Write("Name");
builder.InsertCell();
builder.Write("Value");
builder.EndRow();
builder.InsertCell();
builder.InsertCell();
builder.EndTable();
TableStyle tableStyle = (TableStyle) doc.Styles.Add(StyleType.Table, "MyTableStyle1");
tableStyle.ConditionalStyles.FirstRow.Shading.BackgroundPatternColor = Color.GreenYellow;
tableStyle.ConditionalStyles.FirstRow.Shading.Texture = TextureIndex.TextureNone;
table.Style = tableStyle;
doc.Save(ArtifactsDir + "WorkingWithTableStylesAndFormatting.DefineConditionalFormatting.docx");

Вы также можете выбрать, к каким частям таблицы применять стили, такие как первая колонка, последняя колонка, полосатые строки. Они перечислены в TableStyleOptions Перечисление и осуществляется через StyleOptions собственность. The TableStyleOptions Перечисление позволяет немного комбинировать эти особенности.

Следующий пример кода показывает, как создать новую таблицу со стилем таблицы:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.StartTable();
// We must insert at least one row first before setting any table formatting.
builder.InsertCell();
// Set the table style used based on the unique style identifier.
table.StyleIdentifier = StyleIdentifier.MediumShading1Accent1;
// Apply which features should be formatted by the style.
table.StyleOptions =
TableStyleOptions.FirstColumn | TableStyleOptions.RowBands | TableStyleOptions.FirstRow;
table.AutoFit(AutoFitBehavior.AutoFitToContents);
builder.Writeln("Item");
builder.CellFormat.RightPadding = 40;
builder.InsertCell();
builder.Writeln("Quantity (kg)");
builder.EndRow();
builder.InsertCell();
builder.Writeln("Apples");
builder.InsertCell();
builder.Writeln("20");
builder.EndRow();
builder.InsertCell();
builder.Writeln("Bananas");
builder.InsertCell();
builder.Writeln("40");
builder.EndRow();
builder.InsertCell();
builder.Writeln("Carrots");
builder.InsertCell();
builder.Writeln("50");
builder.EndRow();
doc.Save(ArtifactsDir + "WorkingWithTableStylesAndFormatting.BuildTableWithStyle.docx");

Фотографии ниже показывают представление Table Styles в Microsoft Word и их соответствующих свойств в Aspose.Words.

formatting-table-style-aspose-words-net

Возьмите форматирование из стиля стола и нанесите его как прямой формат

Aspose.Words также обеспечивает ExpandTableStylesToDirectFormatting Способ взять форматирование, найденное в стиле стола, и расширить его на строки и ячейки стола в качестве прямого форматирования. Попробуйте сочетать форматирование со стилем стола и стилем ячейки.

Следующий пример кода показывает, как расширить форматирование от стилей до строк таблиц и ячеек в качестве прямого форматирования:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Tables.docx");
// Get the first cell of the first table in the document.
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
Cell firstCell = table.FirstRow.FirstCell;
// First print the color of the cell shading.
// This should be empty as the current shading is stored in the table style.
Color cellShadingBefore = firstCell.CellFormat.Shading.BackgroundPatternColor;
Console.WriteLine("Cell shading before style expansion: " + cellShadingBefore);
doc.ExpandTableStylesToDirectFormatting();
// Now print the cell shading after expanding table styles.
// A blue background pattern color should have been applied from the table style.
Color cellShadingAfter = firstCell.CellFormat.Shading.BackgroundPatternColor;
Console.WriteLine("Cell shading after style expansion: " + cellShadingAfter);