Застосовувати стиль столу

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

Aspose.Words підтримує нанесення стилю таблиці до столу, а також читання властивостей будь-якого стилю столу. Стилі таблиці зберігаються під час завантаження та збереження за наступними способами:

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

Створити стиль таблиці

Користувач може створити новий стиль і додати його до колекції стилю. Про нас 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 тип занурення. Про нас 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 майно. Про нас 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);