Is it possible to ignore Excel warnings when generating spreadsheets using EPPlus?

痞子三分冷 提交于 2019-11-28 01:07:47

You really have 2 options using code:

  • change the .NumberFormat property of Range to TEXT (I believe equivalent in epplus is Cell[row, column].Style.NumberFormat.Format)

  • prefix any number with ' (a single quote) - Excel then treats the number as TEXT - visually, it displays the number as is but the formula will show the single quote.

Alternatively, which I wouldn't recommend relying on

  • play with Excel's properties and untick the option to display warnings
Christian Sauer

From the EPPlus documentation:

My number formats does not work If you add numeric data as strings (like the original ExcelPackage does), Excel will treat the data as a string and it will not be formatted. Do not use the ToString method when setting numeric values.

string s="1000"
int i=1000;
worksheet.Cells["A1"].Value=s; //Will not be formatted
worksheet.Cells["A2"].Value=i; //Will be formatted
worksheet.Cells["A1:A2"].Style.Numberformat.Format="#,##0";

http://epplus.codeplex.com/wikipage?title=FAQ&referringTitle=Documentation

This is a derivation of TechnoPriest's answer that works for me - I've added handling of decimal values, and changed the name of the method to more accurately document its true raison d'etre:

public static void ConvertValueToAppropriateTypeAndAssign(this ExcelRangeBase range, object value)
{
    string strVal = value.ToString();
    if (!String.IsNullOrEmpty(strVal))
    {
        decimal decVal;
        double dVal;
        int iVal;

        if (decimal.TryParse(strVal, out decVal))
        {
            range.Value = decVal;
        }
        else if (double.TryParse(strVal, out dVal))
        {
            range.Value = dVal;
        }
        else if (Int32.TryParse(strVal, out iVal))
        {
            range.Value = iVal;
        }
        else
        {
            range.Value = strVal;
        }
    }
    else
    {
        range.Value = null;
    }
}

You can check if your value is integer, convert it to int and assign number to cell's value. Then it will be saved as number, not string.

public static void SetValueIntOrStr(this ExcelRangeBase range, object value)
{
    string strVal = value.ToString();
    if (!String.IsNullOrEmpty(strVal))
    {
        double dVal;
        int iVal;

        if (double.TryParse(strVal, out dVal))
            range.Value = dVal;
        else if (Int32.TryParse(strVal, out iVal))
            range.Value = iVal;
        else
            range.Value = strVal;
    }
    else
        range.Value = null;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!