EPPlus不是';t向ExcelHorizontalAlignment Center或Right致敬

本文关键字:Center ExcelHorizontalAlignment Right 致敬 不是 EPPlus | 更新日期: 2023-09-27 18:29:19

我在EPPlus 3.1.3.0和最新的4.0.4.0版本中尝试过这一点,但两者都表现出相同的行为。

我正在尝试在单元格中居中对齐文本,但它不起作用。单元格中的数字工作正常,字符串则不然。以下是无法生成所需ExcelHorizontalAlignment:的代码示例

var newFile = new FileInfo(@"C:'Temp'sample.xlsx");
using (var package = new ExcelPackage(newFile))
{
    var workSheet = package.Workbook.Worksheets.Add("Content");
    workSheet.Column(1).Width = 50;
    workSheet.Cells["A1"].Value = "This should be left-aligned";
    workSheet.Cells["A1"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;

    workSheet.Cells["A2"].Value = "This should be center-aligned";
    workSheet.Cells["A2"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;      // <- This  doesn't work.
    workSheet.Cells["A3"].RichText.Add("This should be center-aligned");
    workSheet.Cells["A3"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;      // <- This  doesn't work.

    workSheet.Cells["A4"].Value = "This should be right-aligned";
    workSheet.Cells["A4"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;       // <- This  doesn't work.
    workSheet.Cells["A5"].RichText.Add("This should be right-aligned");
    workSheet.Cells["A5"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;       // <- This  doesn't work.

    //workSheet.Cells["A2:A3"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; // <- This  doesn't work.
    //workSheet.Cells["A4:A5"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; // <- This  doesn't work.
    package.Save();
}

这让我有点疯狂。你知道为什么字符串不能对齐吗?

EPPlus不是';t向ExcelHorizontalAlignment Center或Right致敬

LibreOffice似乎有部分错误。如果使用EPPlus生成文件,并在"计算"中打开它,则不会显示"居中和向右对齐"。如果我在EPPlus中打开该文件,则格式为"常规"。

但是,如果我使用EPPlus生成文件并立即在EPPlus中读取,则对齐方式与指定的一致。

我确实有一个可以在Calc和Excel中使用的解决方案。如果我创建了一个NamedStyle,并将其应用于单元格或单元格区域,那么一切都会按预期进行。

var newFile = new FileInfo(filePath);
using (var package = new ExcelPackage(newFile))
{
    var workSheet = package.Workbook.Worksheets.Add("Content");
    workSheet.Column(1).Width = 50;
    workSheet.Cells["A1"].Value = "This should be left-aligned";
    workSheet.Cells["A1"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
    var centerStyle = package.Workbook.Styles.CreateNamedStyle("Center");
    centerStyle.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
    workSheet.Cells["A2"].Value = "This should be center-aligned";
    workSheet.Cells["A3"].RichText.Add("This should be center-aligned");
    workSheet.Cells["A2:A3"].StyleName = "Center";
    var rightStyle = package.Workbook.Styles.CreateNamedStyle("Right");
    rightStyle.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
    workSheet.Cells["A4"].Value = "This should be right-aligned";
    workSheet.Cells["A5"].RichText.Add("This should be right-aligned");
    workSheet.Cells["A4:A5"].StyleName = "Right";
    package.Save();
}