9. 行高与列宽¶
本章介绍行高与列宽的设置、按内容估算列宽,以及写出时的自动适配。
Warning
行高与列宽支持 xlsx / xlsm / xlsb / xls 四格式。写出到 csv 时被丢弃,经 OnDegradation 上报(见第 22 章)。
9.1 设置行高¶
Worksheet.RowHeights 为 Dictionary<int, double>:
var ws = Excel.Create().Worksheets["Sheet1"];
ws.SetValue("A1", "Tall row");
ws.RowHeights = new Dictionary<int, double> { { 0, 30.0 } }; // 第 1 行高 30 磅
| 参数 | 类型 | 说明 |
|---|---|---|
| key | int |
0-based 行索引 |
| value | double |
行高,单位磅(point) |
9.2 设置列宽¶
Worksheet.ColumnWidths 为 Dictionary<int, double>:
| 参数 | 类型 | 说明 |
|---|---|---|
| key | int |
0-based 列索引 |
| value | double |
列宽值 |
9.3 列宽自适应 AutoColumnWidths¶
Worksheet.AutoColumnWidths() 按表内现有内容估算每列宽度(中文字符算 2,英文 / 数字算 1,范围 [8, 50]),结果写入 ColumnWidths:
var ws = Excel.Create().Worksheets["Sheet1"];
ws.SetValue("A1", "Name");
ws.SetValue("A2", "Zhang San");
ws.SetValue("B1", "Description");
ws.SetValue("B2", "A very long description that should widen the column");
ws.AutoColumnWidths();
读回验证:
var opened = Excel.Open("autowidth.xlsx");
var widths = opened.Worksheets[0].ColumnWidths;
if (widths is not null)
foreach (var kv in widths)
Console.WriteLine($"Col {kv.Key}: {kv.Value:F1}");
输出:
⚠️
AutoColumnWidths为估算值(中文字符按 2、英文 / 数字按 1,钳制在[8, 50]),与 Excel 实际渲染宽度可能有细微差异。
写出时自动适配:Excel.Write 的 ExcelWriteOptions.AutoFitColumns = true 在写出前对每张表自动估算列宽(ExcelWriteOptions 见第 3 章):
var wb = Excel.Create();
wb.Worksheets["Sheet1"].SetValue("A1", "自动适配列宽");
Excel.Write("out.xlsx", wb, new ExcelWriteOptions { AutoFitColumns = true });
输出: