C# Aspose.Words: 使用指定字符串自动调整表格单元格大小
以下是使用 Aspose.Words 实现输入指定字符串并自动修改字体、调整表格单元格大小适应固定行高和列宽的示例代码:
using Aspose.Words;
using Aspose.Words.Tables;
public void InsertTextAndResizeTable(string text)
{
// 加载文档
Document doc = new Document('input.docx');
// 找到文档中的第一个表格
Table table = doc.GetChildNodes(NodeType.Table, true)[0] as Table;
// 基于固定列宽计算每列的最大宽度
double columnWidth = table.PreferredWidth.Points / table.FirstRow.Cells.Count;
double[] columnWidths = new double[table.FirstRow.Cells.Count];
for (int i = 0; i < table.FirstRow.Cells.Count; i++)
{
columnWidths[i] = columnWidth;
}
// 调整行高以适应文本
double rowHeight = table.Rows[0].RowFormat.Height.Points;
Font font = new Font('Arial', 12);
double maxHeight = 0;
foreach (string line in text.Split('
'))
{
SizeF size = TextRenderer.MeasureText(line, font);
double height = size.Height / 72; // 将像素转换为磅
maxHeight = Math.Max(maxHeight, height);
}
double heightDiff = maxHeight - rowHeight;
if (heightDiff > 0)
{
table.Rows[0].RowFormat.HeightRule = HeightRule.Exactly;
table.Rows[0].RowFormat.Height = ConvertUtil.InchToPoint(maxHeight / 72);
}
// 更新单元格内容并调整单元格大小以适应文本
for (int i = 0; i < table.FirstRow.Cells.Count; i++)
{
Cell cell = table.FirstRow.Cells[i];
cell.RemoveAllChildren();
cell.CellFormat.Width = columnWidths[i];
cell.CellFormat.WrapText = true;
cell.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
Paragraph para = new Paragraph(doc);
para.ParagraphFormat.Alignment = ParagraphAlignment.Center;
para.AppendChild(new Run(doc, text));
cell.AppendChild(para);
double width = cell.CellFormat.Width;
foreach (Paragraph para in cell.Paragraphs)
{
SizeF size = TextRenderer.MeasureText(para.GetText(), font);
double paraWidth = size.Width / 72; // 将像素转换为磅
width = Math.Max(width, paraWidth);
}
cell.CellFormat.Width = width;
}
// 保存修改后的文档
doc.Save('output.docx');
}
此示例假定文档中只有一个表格,并且该表格的第一行包含所有列的标题。它首先计算每个列的最大宽度,然后将行高调整为适合文本的最大高度。然后,它更新每个单元格的内容,并调整单元格宽度以适应文本。最后,它保存修改后的文档。
原文地址: https://www.cveoy.top/t/topic/nKd3 著作权归作者所有。请勿转载和采集!