2

我已经在 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();
}

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

4

1 回答 1

2

似乎 LibreOffice 有部分错误。如果我使用 EPPlus 生成文件,并在 Calc 中打开它,则不会显示居中对齐和右对齐。如果我随后在 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();
}
于 2016-01-08T18:38:36.490 回答