מרק שולחן תאים

לפעמים שורות מסוימות בטבלה דורשות כותרת או בלוקים גדולים של טקסט לקחת את רוחב המלא של השולחן. עבור עיצוב תקין של השולחן, המשתמש יכול למזג כמה תאים בטבלה לתוך אחד. Aspose.Words תומך תאים ממוזגים כאשר עובדים עם כל פורמטי קלט, כולל ייבוא תוכן HTML.

איך להגות Table Cells

In In In Aspose.Words, תאים ממוזגים על ידי התכונות הבאות של CellFormat קטגוריה:

    • HorizontalMerge המתאר אם התא הוא חלק ממיזוג אופקי של תאים
    • VerticalMerge המתאר אם התא הוא חלק ממיזוג אנכי של תאים

הערכים של תכונות אלה קובעים את התנהגות המיזוג של תאים:

בדוק אם Cell is Merged

כדי לבדוק אם תא הוא חלק מרצף של תאים ממוזגים, אנחנו פשוט בודקים את התא. HorizontalMerge ו VerticalMerge תכונות.

הדוגמה הבאה של הקוד מראה כיצד להדפיס את סוג התא האופקי והארכיני:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Table with merged cells.docx");
Table table = (Table) doc.GetChild(NodeType.Table, 0, true);
foreach (Row row in table.Rows)
{
foreach (Cell cell in row.Cells)
{
Console.WriteLine(PrintCellMergeType(cell));
}
}

מארג' טבלה Cells When Using DocumentBuilder

למזג תאים בטבלה שנוצרה עם DocumentBuilder, אתה צריך להגדיר את סוג המיזוג המתאים לכל תא שבו המיזוג צפוי - הראשון CellMerge.First ואז CellMerge.Previous.

כמו כן, עליך לזכור לנקות את הגדרת המיזוג עבור תאים אלה שבהם אין צורך במיזוג - זה יכול להיעשות על ידי הגדרת תא non-merge הראשון. CellMerge.None. אם זה לא נעשה, כל התאים בטבלה יתמזגו.

דוגמה הקוד הבא מראה כיצד ליצור שולחן עם שתי שורות שבו התאים בשורה הראשונה מתמזגים אופקית:

// 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);
builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.First;
builder.Write("Text in merged cells.");
builder.InsertCell();
// This cell is merged to the previous and should be empty.
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
builder.EndRow();
builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.None;
builder.Write("Text in one cell.");
builder.InsertCell();
builder.Write("Text in another cell.");
builder.EndRow();
builder.EndTable();
doc.Save(ArtifactsDir + "WorkingWithTables.HorizontalMerge.docx");

הדוגמה הבאה של הקוד מראה כיצד ליצור שולחן דו-מושבי שבו התאים בעמודה הראשונה מתמזגים אנכית:

// 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);
builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.First;
builder.Write("Text in merged cells.");
builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("Text in one cell");
builder.EndRow();
builder.InsertCell();
// This cell is vertically merged to the cell above and should be empty.
builder.CellFormat.VerticalMerge = CellMerge.Previous;
builder.InsertCell();
builder.CellFormat.VerticalMerge = CellMerge.None;
builder.Write("Text in another cell");
builder.EndRow();
builder.EndTable();
doc.Save(ArtifactsDir + "WorkingWithTables.VerticalMerge.docx");

תאי שולחן במקרים אחרים

במצבים אחרים שבהם DocumentBuilder לא משמש, כגון בטבלה קיימת, מיזוג תאים בדרך הקודמת לא יכול להיות קל. במקום זאת, אנו יכולים לעטוף את הפעולות הבסיסיות הכרוכות ביישום תכונות מיזוג לתאים בשיטה שהופכת את המשימה להרבה יותר קלה. שיטה זו דומה לשיטת האוטומציה של Merge, הנקראת למזג מגוון תאים בטבלה.

הקוד להלן ימזג את תאי הטבלה בטווח שצוין, החל מהתא נתון וסיום בתא הסופי. במקרה זה, הטווח יכול לעגל שורות מרובות או עמודות:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
internal void MergeCells(Cell startCell, Cell endCell)
{
Table parentTable = startCell.ParentRow.ParentTable;
// Find the row and cell indices for the start and end cell.
Point startCellPos = new Point(startCell.ParentRow.IndexOf(startCell),
parentTable.IndexOf(startCell.ParentRow));
Point endCellPos = new Point(endCell.ParentRow.IndexOf(endCell), parentTable.IndexOf(endCell.ParentRow));
// Create a range of cells to be merged based on these indices.
// Inverse each index if the end cell is before the start cell.
Rectangle mergeRange = new Rectangle(Math.Min(startCellPos.X, endCellPos.X),
Math.Min(startCellPos.Y, endCellPos.Y),
Math.Abs(endCellPos.X - startCellPos.X) + 1, Math.Abs(endCellPos.Y - startCellPos.Y) + 1);
foreach (Row row in parentTable.Rows)
{
foreach (Cell cell in row.Cells)
{
Point currentPos = new Point(row.IndexOf(cell), parentTable.IndexOf(row));
// Check if the current cell is inside our merge range, then merge it.
if (mergeRange.Contains(currentPos))
{
cell.CellFormat.HorizontalMerge = currentPos.X == mergeRange.X ? CellMerge.First : CellMerge.Previous;
cell.CellFormat.VerticalMerge = currentPos.Y == mergeRange.Y ? CellMerge.First : CellMerge.Previous;
}
}
}
}
view raw merge-cells.cs hosted with ❤ by GitHub

לדוגמה הקוד הבא מראה כיצד למזג טווח תאים בין שני תאים מוגדרים:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Table with merged cells.docx");
Table table = doc.FirstSection.Body.Tables[0];
// We want to merge the range of cells found inbetween these two cells.
Cell cellStartRange = table.Rows[0].Cells[0];
Cell cellEndRange = table.Rows[1].Cells[1];
// Merge all the cells between the two specified cells into one.
MergeCells(cellStartRange, cellEndRange);
doc.Save(ArtifactsDir + "WorkingWithTables.MergeCellRange.docx");

בהתאם לגרסה של .NET Framework אתה משתמש, ייתכן שתרצה לחדד שיטה זו על ידי הפיכתה לשיטת הרחבה. במקרה זה, אתה יכול לקרוא שיטה זו ישירות על תא כדי למזג מגוון של תאים, כגון: cell1.Merge(cell2).

Vertical and Horizontal Merged Cells in HTML Table

כפי שאמרתי במאמרים קודמים, שולחן Microsoft Word היא קבוצה של שורות עצמאיות. לכל שורה יש קבוצה של תאים שאינם תלויים בתאים של שורות אחרות. כך, ב Microsoft Word טבלה אין אובייקט כזה “שטח”, ו"עמודה ראשונה" הוא משהו כמו “מערך התאים הראשונים של כל שורה בטבלה”. זה מאפשר למשתמשים יש שולחן שבו, לדוגמה, השורה הראשונה מורכבת משני תאים - 2 ס"מ ו 1 ס"מ, ואת השורה 2 מורכב משני תאים שונים - 1 ס"מ ו 2 ס"מ רחב. ו Aspose.Words תומך ברעיון זה של טבלאות.

בטבלה ב- HTML יש מבנה שונה לחלוטין: לכל שורה יש את אותו מספר תאים (חשוב למשימה) לכל תא יש את רוחב העמודה המקבילה, אותו הדבר לכל התאים בעמודה אחת. אם HorizontalMerge ו VerticalMerge להחזיר ערך לא נכון, השתמש בדוגמה הבאה:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Table with merged cells.docx");
SpanVisitor visitor = new SpanVisitor(doc);
doc.Accept(visitor);
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
/// <summary>
/// Helper class that contains collection of rowinfo for each row.
/// </summary>
public class TableInfo
{
public List<RowInfo> Rows { get; } = new List<RowInfo>();
}
/// <summary>
/// Helper class that contains collection of cellinfo for each cell.
/// </summary>
public class RowInfo
{
public List<CellInfo> Cells { get; } = new List<CellInfo>();
}
/// <summary>
/// Helper class that contains info about cell. currently here is only colspan and rowspan.
/// </summary>
public class CellInfo
{
public CellInfo(int colSpan, int rowSpan)
{
ColSpan = colSpan;
RowSpan = rowSpan;
}
public int ColSpan { get; }
public int RowSpan { get; }
}
public class SpanVisitor : DocumentVisitor
{
/// <summary>
/// Creates new SpanVisitor instance.
/// </summary>
/// <param name="doc">
/// Is document which we should parse.
/// </param>
public SpanVisitor(Document doc)
{
mWordTables = doc.GetChildNodes(NodeType.Table, true);
// We will parse HTML to determine the rowspan and colspan of each cell.
MemoryStream htmlStream = new MemoryStream();
Aspose.Words.Saving.HtmlSaveOptions options = new Aspose.Words.Saving.HtmlSaveOptions
{
ImagesFolder = Path.GetTempPath()
};
doc.Save(htmlStream, options);
// Load HTML into the XML document.
XmlDocument xmlDoc = new XmlDocument();
htmlStream.Position = 0;
xmlDoc.Load(htmlStream);
// Get collection of tables in the HTML document.
XmlNodeList tables = xmlDoc.DocumentElement.GetElementsByTagName("table");
foreach (XmlNode table in tables)
{
TableInfo tableInf = new TableInfo();
// Get collection of rows in the table.
XmlNodeList rows = table.SelectNodes("tr");
foreach (XmlNode row in rows)
{
RowInfo rowInf = new RowInfo();
// Get collection of cells.
XmlNodeList cells = row.SelectNodes("td");
foreach (XmlNode cell in cells)
{
// Determine row span and colspan of the current cell.
XmlAttribute colSpanAttr = cell.Attributes["colspan"];
XmlAttribute rowSpanAttr = cell.Attributes["rowspan"];
int colSpan = colSpanAttr == null ? 0 : int.Parse(colSpanAttr.Value);
int rowSpan = rowSpanAttr == null ? 0 : int.Parse(rowSpanAttr.Value);
CellInfo cellInf = new CellInfo(colSpan, rowSpan);
rowInf.Cells.Add(cellInf);
}
tableInf.Rows.Add(rowInf);
}
mTables.Add(tableInf);
}
}
public override VisitorAction VisitCellStart(Cell cell)
{
int tabIdx = mWordTables.IndexOf(cell.ParentRow.ParentTable);
int rowIdx = cell.ParentRow.ParentTable.IndexOf(cell.ParentRow);
int cellIdx = cell.ParentRow.IndexOf(cell);
int colSpan = 0;
int rowSpan = 0;
if (tabIdx < mTables.Count &&
rowIdx < mTables[tabIdx].Rows.Count &&
cellIdx < mTables[tabIdx].Rows[rowIdx].Cells.Count)
{
colSpan = mTables[tabIdx].Rows[rowIdx].Cells[cellIdx].ColSpan;
rowSpan = mTables[tabIdx].Rows[rowIdx].Cells[cellIdx].RowSpan;
}
Console.WriteLine("{0}.{1}.{2} colspan={3}\t rowspan={4}", tabIdx, rowIdx, cellIdx, colSpan, rowSpan);
return VisitorAction.Continue;
}
private readonly List<TableInfo> mTables = new List<TableInfo>();
private readonly NodeCollection mWordTables;
}

עקבו אחרי Horizontally תאים מרורגים

לפעמים לא ניתן לזהות אילו תאים מתמזגים כי כמה גרסאות חדשות יותר של Microsoft Word כבר לא להשתמש דגלי המיזוג כאשר תאים מתמזגים אופקית. אבל עבור מצבים שבהם תאים מתמזגים לתוך תא אופקית על ידי רוחבם באמצעות דגלים מתמזגים, Aspose.Words מספק ConvertToHorizontallyMergedCells שיטה להמיר תאים שיטה זו פשוט הופכת את השולחן ומוסיפה תאים חדשים במידת הצורך.

הדוגמה הבאה מציגה את השיטה לעיל בפעולה:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Table with merged cells.docx");
Table table = doc.FirstSection.Body.Tables[0];
// Now merged cells have appropriate merge flags.
table.ConvertToHorizontallyMergedCells();