【问题标题】:How to get a value from Excel spreadsheet cell using EPPLUS?如何使用 EPPLUS 从 Excel 电子表格单元格中获取值?
【发布时间】:2016-03-15 16:45:05
【问题描述】:

我正在使用 EPPlus 库从数据表创建 excel。

这就是我的工作:

using (ExcelPackage pck = new ExcelPackage())
{
   ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
   ws.Cells["A5:I5"].LoadFromDataTable(dt, true); 
   ws.DefaultColWidth = 25;

   var headerCell = ws.Cells["A5:I5"];
   headerCell.Style.Fill.PatternType = ExcelFillStyle.Solid;
   headerCell.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.BurlyWood);
   var headerFont = headerCell.Style.Font;
   headerFont.Bold = true; 

   int totalRow = ws.Dimension.End.Row;
   int totalCol = ws.Dimension.End.Column;
   using (ExcelRange rng = ws.Cells[6,1,totalRow,totalCol])   
   {
       rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
       rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Bisque);

       long n = 0;
       for (int row = 6; row <= totalRow; row++)
       {
           for (int col = 1; col <= 9; col++)
           {
                string colVol = (string)ws.Cells[row, col].Value;
                bool isNumeric = long.TryParse(colVol, out n);
                if (isNumeric && colVol.Length > 10)
                {
                      //ws.Cells[row, col] //need to apply a css style
                }
           }
       }
   }
   ws.Cells["A4"].LoadFromText(name);
   Response.AddHeader("content-disposition", "inline;filename=" + name + ".xls");
   Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
   Response.BinaryWrite(pck.GetAsByteArray());   
}

我需要将样式应用于电子表格中满足特定条件的某些单元格。

这是之前代码在循环中构建表格时的做法:

for (int i = 0; i < dt.Columns.Count; i++)
{
    td = new TableCell();
    td.Text = dt.Rows[j][i].ToString();

    n = 0;
    bool isNumeric = long.TryParse(td.Text, out n);
    if (isNumeric && td.Text.Length > 10)
       td.Attributes.Add("style", @"mso-number-format:\@");

    tr.Cells.Add(td);
 }

如何从单元格中获取值以检查使用 EPPlus 方法格式化值的条件?

【问题讨论】:

  • 您在陈述两个需求。如果条件为真,您要格式化 所有 值还是仅格式化其中的一部分?
  • 无论如何,您可能会在这里找到答案:stackoverflow.com/questions/28698226/…
  • 如果我正确阅读了您的编辑(您正在使用 HTML 元素),您是否希望在这种情况下强制使用文本格式?为什么你不能只做ws.Cells[row, col].Style.Numberformat.Format = "@";?这将告诉 excel 使用文本格式而不是数字。
  • 谢谢。我想这就是我一直在寻找的

标签: c# datatable epplus


【解决方案1】:

(更新答案以反映 OP 问题编辑和 cmets)

只要做:

ws.Cells[row, col].Style.Numberformat.Format = "@";

这将告诉 excel 使用文本格式而不是数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多