I am inserting multiple html tables with class property using insertHtml method. How can I find table with specific class names and based on table name I need to need to set style in aspose.
To find a table with a specific class name after inserting multiple HTML tables using the insertHtml method in Aspose.Words, you can follow these steps:
-
Insert HTML with Class Names: When you insert HTML tables, ensure that each table has a unique class name in the HTML markup.
-
Access the Document’s Tables: After inserting the HTML, you can access the tables in the document using the
getChildNodesmethod. -
Filter Tables by Class Name: Iterate through the tables and check the class name of each table. You can do this by examining the properties of the table or its cells.
-
Apply Styles: Once you find the table with the desired class name, you can modify its style properties as needed.
Here is a code example demonstrating how to achieve this:
import com.aspose.words.*;
public class FindTableByClassName {
public static void main(String[] args) throws Exception {
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert HTML with tables having class names
String html = "<table class='myClass'><tr><td>Cell 1</td></tr></table>" +
"<table class='anotherClass'><tr><td>Cell 2</td></tr></table>";
builder.insertHtml(html);
// Access all tables in the document
NodeCollection tables = doc.getChildNodes(NodeType.TABLE, true);
for (int i = 0; i < tables.getCount(); i++) {
Table table = (Table) tables.get(i);
// Check for the specific class name
if (table.getStyleName().equals("myClass")) {
// Apply styles to the found table
table.setBorders(LineStyle.SINGLE, 1.0, Color.RED);
table.setAlignment(TableAlignment.CENTER);
// Additional styling can be applied here
}
}
// Save the modified document
doc.save("ModifiedDocument.docx");
}
}
In this example, we insert HTML containing two tables with different class names. We then iterate through the tables in the document, checking for the class name “myClass” and applying styles to it. You can adjust the class name and styles as per your requirements.
Make sure to replace the class name check with the appropriate method to retrieve the class name if you are using a different approach to set class names in your HTML.
Getstylename not method. I am not getting this option.
@Ragulkr I am afraid there is no way to identify table imported from HTML by it’s class name in Aspose.Words DOM. You should note, that Aspose.Words is designed to work with MS Word documents. HTML documents and MS Word documents object models are quite different and it is not always possible to provide 100% fidelity after conversion one model to another. In most cases Aspose.Words mimics MS Word behavior when work with HTML.