EPPlus不支持ExcelHorizo​​ntalAlignment Center或Right

时间:2016-01-07 16:41:01

标签: c# epplus epplus-4

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

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

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();
}

这让我有点疯狂。任何想法为什么字符串不能对齐?

1 个答案:

答案 0 :(得分:2)

好像LibreOffice部分有问题。如果我使用EPPlus生成文件,并在Calc中打开它,则不会显示中心和右对齐。如果我然后在EPPlus中打开文件,则格式为General。

但是,如果我使用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();
}