C# Excel 中设置文字对齐方式、方向和换行

时间:2022-04-19 10:51:20

在Excel表格中输入文字时,我们常常需要调整文字对齐方式或者对文字进行换行。本文将介绍如何通过编程的方式设置文字对齐方式,改变文字方向以及对文字进行换行。

//创建Workbook对象
Workbook wookbook = new Workbook();
Worksheet sheet = wookbook.Worksheets[0]; //添加说明文字
sheet.Range["B1"].Text = "文字对齐方式";
sheet.Range["D1"].Text = "文字方向";
sheet.Range["F1"].Text = "文字换行";
sheet.Range["B1:F1"].Style.Font.IsBold = true; //左对齐
sheet.Range["B3"].Text = "左对齐";
sheet.Range["B3"].Style.HorizontalAlignment = HorizontalAlignType.Left; //水平居中
sheet.Range["B4"].Text = "水平居中";
sheet.Range["B4"].Style.HorizontalAlignment = HorizontalAlignType.Center; //右对齐
sheet.Range["B5"].Text = "右对齐";
sheet.Range["B5"].Style.HorizontalAlignment = HorizontalAlignType.Right; //居上
sheet.Range["B7"].Text = "居上";
sheet.Range["B7"].Style.VerticalAlignment = VerticalAlignType.Top; //居中
sheet.Range["B8"].Text = "垂直居中";
sheet.Range["B8"].Style.VerticalAlignment = VerticalAlignType.Center; //居下
sheet.Range["B9"].Text = "居下";
sheet.Range["B9"].Style.VerticalAlignment = VerticalAlignType.Bottom; //分散对齐并居中
sheet.Range["B10"].Text = "水平分散对齐+垂直居中";
sheet.Range["B10"].Style.HorizontalAlignment = HorizontalAlignType.Distributed;
sheet.Range["B10"].Style.VerticalAlignment = VerticalAlignType.Center; //逆时针旋转45°
sheet.Range["D7"].Text = "旋转45°";
sheet.Range["D7"].Style.Rotation = 45; //逆时针旋转90°
sheet.Range["D8"].Text = "旋转90°";
sheet.Range["D8"].Style.Rotation = 90; //顺时针旋转45°
sheet.Range["D9"].Text = "旋转-45°";
sheet.Range["D9"].Style.Rotation = 135; //顺时针旋转90°
sheet.Range["D10"].Text = "旋转-90°";
sheet.Range["D10"].Style.Rotation = 180; //添加‘\n’进行文字换行
sheet.Range["F9"].Text = "这是\n手动\n换行"; //自动换行
sheet.Range["F10"].Text = "这是自动换行(额外测试文字)";
sheet.Range["F10"].Style.WrapText = true; //设置列宽、行高
sheet.Columns[1].ColumnWidth = 15;
sheet.Columns[3].ColumnWidth = 15;
sheet.Columns[5].ColumnWidth = 15;
sheet.Range["B3:B5"].RowHeight = 15;
sheet.Range["B7:B10"].RowHeight = 50; //保存文档
wookbook.SaveToFile("TextAlignment.xlsx", FileFormat.Version2013);

C# Excel 中设置文字对齐方式、方向和换行