如何使用EPPLUS从Excel电子表格单元格获取值? [英] How to get a value from Excel spreadsheet cell using EPPLUS?

查看:3051
本文介绍了如何使用EPPLUS从Excel电子表格单元格获取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EPPlus库从datatable创建excel。

I'm using EPPlus library to create excel from datatable.

这是我做的:

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

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

I need to apply the styles to some cells in spreadsheet that meet certain condition.

这是代码在循环中构建表时的方式:

This is how it is done before when code was building the table in the loop:

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方法的价值?

How can I get the value from the cell to check for the condition to format the value using EPPlus approach?

推荐答案

(更新答案反映OP问题编辑和评论)

(updated answer to reflect OP Question edits and comments)

只要做:

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

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

This will tell excel to use a text format instead of numeric.

这篇关于如何使用EPPLUS从Excel电子表格单元格获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆