如何将包裹的列标题水平对齐?

时间:2015-12-18 16:35:39

标签: c# centering excel-interop

我正在创建一个"列标题行"在Excel电子表格上,最终看起来像这样:

enter image description here

请注意跨越多个"行的列标题"未在其单元格内水平对齐。最后一行""似乎是以中心为中心,但在它之前/之上的那些偏离中心。例如,使用"会员条款代码","会员"是方式在左边太远了,"项目"也是左边太远(但不那么),而#34; Code"看起来很完美但显然我的代码并不是很完美。

应用" center"的水平对齐对这些细胞:

var unitHeaderCell = (Excel.Range)_xlSheet.Cells[rowToPopulate, DETAIL_UNIT_COL];
unitHeaderCell.Value2 = "Unit";

var custNumHeaderCell = (Excel.Range)_xlSheet.Cells[rowToPopulate, DETAIL_CUSTNUM_COL];
custNumHeaderCell.Value2 = String.Format("Customer{0}Number", Environment.NewLine);
custNumHeaderCell.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
custNumHeaderCell.WrapText = true;

var custNameHeaderCell = (Excel.Range)_xlSheet.Cells[rowToPopulate, DETAIL_CUSTNAME_COL];
custNameHeaderCell.Value2 = String.Format("Customer{0}Name", Environment.NewLine);
custNameHeaderCell.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
custNameHeaderCell.WrapText = true;

var memberItemCodeHeaderCell = (Excel.Range)_xlSheet.Cells[rowToPopulate, DETAIL_MEMBERITEMCODE_COL];
memberItemCodeHeaderCell.Value2 = String.Format("Member{0}Item{0}Code", Environment.NewLine);
memberItemCodeHeaderCell.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
memberItemCodeHeaderCell.WrapText = true;
memberItemCodeHeaderCell.ColumnWidth = DETAIL_MEMBERITEMCODE_COL_WIDTH;

var qtyHeaderCell = (Excel.Range)_xlSheet.Cells[rowToPopulate, DETAIL_QTY_COL];
qtyHeaderCell.Value2 = "Qty";

var bidPriceHeaderCell = (Excel.Range)_xlSheet.Cells[rowToPopulate, DETAIL_BIDPRICE_COL];
bidPriceHeaderCell.Value2 = "Bid Price";

我必须做些什么才能将所有这些词放在中心(而不仅仅是最后一个)?

1 个答案:

答案 0 :(得分:2)

您不需要在单词之间添加Environment.NewLine,您可以简单地在单词之间使用空格并包装列的内容,并根据列宽,它将以多行显示。

在下面的代码中,我设置范围内的所有单元格以包装文本,并垂直和水平居中。

同样仅用于测试我设置第5列的列宽。

//Using
using XL = Microsoft.Office.Interop.Excel;

//Code
XL.Application application = new XL.Application();
application.Visible = true;
var book = application.Workbooks.Add();
var sheet = book.Worksheets[1];

sheet.Cells[1, 1].Value2 = "Unit";
sheet.Cells[1, 2].Value2 = "Customer Number";
sheet.Cells[1, 3].Value2 = "Customer Name";
sheet.Cells[1, 4].Value2 = "Member Item Code";
sheet.Cells[1, 5].Value2 = "Qty";
sheet.Cells[1, 5].ColumnWidth = 30;
sheet.Cells[1, 6].Value2 = "Bad Price";

var range = sheet.Range("A1", "F1");
range.VerticalAlignment = XL.XlVAlign.xlVAlignCenter;
range.HorizontalAlignment = XL.XlHAlign.xlHAlignCenter;
range.WrapText = true;

以下是默认字体设置的结果:

enter image description here

这是使用自定义字体设置的结果:

range.Font.Name = "Tahoma";
range.Font.Bold = true;
range.Font.Size = 9;

enter image description here