c# - 使用 EPPLUS Excel 库格式化列

标签 c# export-to-excel epplus number-formatting

我编写了一个 C# 程序来创建 Excel 电子表格。该工作表有多个列。我想格式化其中一列。

aFile = new FileInfo(excelDocName); // excelDocName is a string
ExcelPackage pck = new ExcelPackage(aFile);
var ws = pck.Workbook.Worksheets.Add("Content");
ws.View.ShowGridLines = true;
ws.Cells["B:B"].Style.Numberformat.Format = "0.00";
ws.Cells[1, 1].Value = "AA";
ws.Cells[1, 2].Value = "BB";
ws.Cells[1, 3].Value = "CC";
ws.Cells[1, 4].Value = "DD";
for (int row = 2; row <= 10; ++row)
  for (int col = 1; col <= 4; ++col)
  {
  ws.Cells[row, col].Value = row * col;
  }
ws.Row(1).Style.Font.Bold = true;
pck.Save();

问题是,虽然它正确地格式化了该列,但它还使用该格式格式化其他列,而不仅仅是我指定的列。 我也试过:

ws.Column(1).Style.Numberformat.Format = "0.00";

这是一个错误还是我遗漏了什么?

最佳答案

您要打开现有文件吗?在您打开它之前,它的格式可能已经应用于其他列。或者像 astian 所说的模板。

清除所有格式以防万一:

ws.Cells["A:D"].Style.Numberformat.Format = null;
ws.Cells["B:B"].Style.Numberformat.Format = "0.00";

EPPlus 4.0.3 中的完整单元测试:

[TestMethod]
public void Format_Single_Column_Test()
{
    //http://stackoverflow.com/questions/28698226/formatting-a-column-with-epplus-excel-library
    var excelDocName = @"c:\temp\temp.xlsx";
    var aFile = new FileInfo(excelDocName); // excelDocName is a string

    if (aFile.Exists)
        aFile.Delete();

    ExcelPackage pck = new ExcelPackage(aFile);
    var ws = pck.Workbook.Worksheets.Add("Content");
    ws.View.ShowGridLines = true;
    ws.Cells["A:D"].Style.Numberformat.Format = null;
    ws.Cells["B:B"].Style.Numberformat.Format = "0.00";
    ws.Cells[1, 1].Value = "AA";
    ws.Cells[1, 2].Value = "BB";
    ws.Cells[1, 3].Value = "CC";
    ws.Cells[1, 4].Value = "DD";
    for (int row = 2; row <= 10; ++row)
        for (int col = 1; col <= 4; ++col)
        {
            ws.Cells[row, col].Value = row*col;
        }
    ws.Row(1).Style.Font.Bold = true;
    pck.Save();
}

关于c# - 使用 EPPLUS Excel 库格式化列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28698226/

相关文章:

r - 将 R 列表保存到单独的 Excel 工作表中的函数

c# - Excel 单元格公式正在使用工作表名称更新。从 ASP.NET 导出

html - 什么是 XLSHTML?

c# - 使用 EPPlus 返回 INT 的 Excel 日期列

c# - 如何在不使用 Invoke 方法的情况下组合两个 lambda 表达式?

c# - 不循环更新数据表中的多行

c# - 如何将基于字符串的时间转换为 hh :mm format in excel using EPPlus?

c# - 如何在 epplus 工作表中附加 HTML?

c# - 转换 11/1/2012 3 :42:09 AM to November 1 , 2012

c# - 在 C# 中避免多个 if 语句