使用EPPlus生成电子表格时是否可以忽略Excel警告?

我使用C#和EPPlus在电子表格的单个列中存储数字和非数字值的混合。 当我用Excel打开电子表格时,它会在数值显示的单元格中显示绿色的三angular形,并给出警告:“数字存储为文本”,并提供忽略特定单元格的选项。 我可以从代码做到这一点,或者它是一些Excel的具体function?

你真的有2个select使用代码:

  • 将Range的.NumberFormat属性更改为TEXT( 我相信epplus中的等价物是Cell[row, column].Style.NumberFormat.Format

  • '单引号'前缀任意数字 – Excel然后将数字视为“文本' (TEXT) – 直观地显示数字,但公式将显示单引号。

另外,我不会build议依靠

  • 玩Excel的属性,并取消select显示警告

从EPPlus文档:

我的数字格式不起作用如果您将数字数据添加为string(如原始ExcelPackage那样),则Excel将把数据视为string,并且不会被格式化。 设置数字值时不要使用ToString方法。

 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

你可以检查你的值是否是整数,将它转换为int并将数值赋给单元格的值。 然后它将被保存为数字,而不是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; } 

这是TechnoPriest对我的解答的一个推导 – 我已经添加了十进制值的处理,并更改了方法的名称以更准确地logging它的真实存在:

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