Прилагане на стил на таблица

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

Aspose.Words поддържа прилагането на стил маса към маса и също така четене свойства на всяка таблица стил. Стиловете на таблиците се запазват по време на товарене и спестяване по следните начини:

  • Table styles in DOCX and WordML формати са запазени при зареждане и запис към тези формати
  • Стиловете на таблица се запазват при зареждане и запис във формат DOC (но не и в друг формат)
  • При износ към други формати, обработка или печат, стиловете на масата се разширяват до директно форматиране в таблицата, така че всички форматиране се запазва

Създаване на стил на таблица

Потребителят може да създаде нов стил и да го добави към колекцията стил. На Add метод се използва за създаване на нов стил маса.

Следният пример за код показва как да се създаде нов потребителски дефиниран стил на таблица:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.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.getStyles().add(StyleType.TABLE, "MyTableStyle1");
tableStyle.getBorders().setLineStyle(LineStyle.DOUBLE);
tableStyle.getBorders().setLineWidth(1.0);
tableStyle.setLeftPadding(18.0);
tableStyle.setRightPadding(18.0);
tableStyle.setTopPadding(12.0);
tableStyle.setBottomPadding(12.0);
table.setStyle(tableStyle);
doc.save(getArtifactsDir() + "WorkingWithTableStylesAndFormatting.CreateTableStyle.docx");

Копиране на съществуващ стил на таблица

Ако е необходимо, можете да копирате стил таблица, която вече съществува в определен документ в колекцията си стил с помощта на AddCopy метод.

Важно е да знаете, че с това копиране, свързаните стилове също се копират.

Следният пример за код показва как се внася стил от един документ в друг документ:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document srcDoc = new Document();
// Create a custom style for the source document.
Style srcStyle = srcDoc.getStyles().add(StyleType.PARAGRAPH, "MyStyle");
srcStyle.getFont().setColor(Color.RED);
// Import the source document's custom style into the destination document.
Document dstDoc = new Document();
Style newStyle = dstDoc.getStyles().addCopy(srcStyle);
// The imported style has an appearance identical to its source style.
Assert.assertEquals("MyStyle", newStyle.getName());
Assert.assertEquals(Color.RED.getRGB(), newStyle.getFont().getColor().getRGB());

Прилагане на съществуващ стил на таблица

Aspose.Words осигурява TableStyle наследени от Style Клас. TableStyle улеснява потребителя да прилага различни опции стил като shading, подплънки, вдлъбнатини, 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-Java.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.getStyles().add(StyleType.TABLE, "MyTableStyle1");
tableStyle.getConditionalStyles().getFirstRow().getShading().setBackgroundPatternColor(Color.yellow);
tableStyle.getConditionalStyles().getFirstRow().getShading().setTexture(TextureIndex.TEXTURE_NONE);
table.setStyle(tableStyle);
doc.save(getArtifactsDir() + "WorkingWithTableStylesAndFormatting.DefineConditionalFormatting.docx");

Можете също така да изберете коя таблица части да се прилагат стилове, като например първата колона, последната колона, ленти редове. Те са изброени в TableStyleOptions изброяване и се прилагат чрез StyleOptions собственост. На TableStyleOptions изброяването позволява малко комбинация от тези функции.

Следният пример за код показва как да се създаде нова таблица с приложен стил на таблица:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.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.setStyleIdentifier(StyleIdentifier.MEDIUM_SHADING_1_ACCENT_1);
// Apply which features should be formatted by the style.
table.setStyleOptions(TableStyleOptions.FIRST_COLUMN | TableStyleOptions.ROW_BANDS | TableStyleOptions.FIRST_ROW);
table.autoFit(AutoFitBehavior.AUTO_FIT_TO_CONTENTS);
builder.writeln("Item");
builder.getCellFormat().setRightPadding(40.0);
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(getArtifactsDir() + "WorkingWithTableStylesAndFormatting.BuildTableWithStyle.docx");

Снимките по-долу показват представяне на Table Styles в Microsoft Word и съответните им свойства в Aspose.Words.

table-style-aspose-words-java

Вземете форматиране от стила на таблица и го нанесете като директно форматиране

Aspose.Words и осигурява ExpandTableStylesToDirectFormatting метод за вземане на форматиране намерени в стил маса и го разширява върху редовете и клетките на таблицата като пряко форматиране. Опитайте се да комбинирате форматиране със стил маса и мобилен стил.

Следният пример за код показва как да се разшири форматирането от стилове върху редове на таблица и клетки като пряко форматиране:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document(getMyDir() + "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.getFirstRow().getFirstCell();
// 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.getCellFormat().getShading().getBackgroundPatternColor();
System.out.println("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.getCellFormat().getShading().getBackgroundPatternColor();
System.out.println("Cell shading after style expansion: " + cellShadingAfter);