【问题标题】:cell in Excel "Number stored as text"Excel中的单元格“数字存储为文本”
【发布时间】:2011-10-28 05:32:04
【问题描述】:

我有一个 C# 程序,它获取旧报告的文本文件并映射到 Excel 工作表。 但对于交易单元,它输出为“数字存储为文本”,这不允许 任何格式。我们想显示 1,000.00,但它只能显示为 1000。

有没有办法获得这种格式?这些列是余额和金额。 在这里定义:

ndcRange = currentSheet.Cells[transactionRowNo + pageOffset, 13];
ndcRange.NumberFormat = "@";
ndcRange.Value2 = tr.Amount;

ndcRange = currentSheet.Cells[transactionRowNo + pageOffset, 16];
ndcRange.NumberFormat = "@";
ndcRange.Value2 = tr.Balance;

这里是一些格式化的代码:

string balance = transaction;

if (lastSpaceIndex != -1)
{

   balance = transaction.Substring(lastSpaceIndex, (transaction.Length)lastSpaceIndex);

}

transac.Balance = balance;
transaction = transaction.Replace(balance, "");


transaction = transaction.Trim();

if (!string.IsNullOrWhiteSpace(transaction))
{
    transac.Description = transaction;
}
patient.TransactionsList.Add(transac);

【问题讨论】:

  • 您如何在 C# 中创建和/或填充工作簿/工作表?有很多方法可以做到这一点,所以答案取决于你在做什么。
  • 你是如何设置单元格值的?

标签: c# excel


【解决方案1】:

使用 Microsoft Excel 对象库中的 Range.NumberFormat。检查这个link

示例代码:

oRng = oSheet.get_Range("C2", "C1000"); //change this range to suit your scenario
oRng.Formula = "<any formula you may be using already or skip it>";
oRng.NumberFormat = "#,##0.00"; 

参考资料:

How to automate Microsoft Excel from Microsoft Visual C#.NET

StackOverflow example

【讨论】:

  • 我认为 Range.NumberFormat 行不通,因为数字存储为文本。
  • 由于他的代码使用 .NumberFormat,数字被存储为文本。他只需要使用正确的格式,而不是使用示例代码中建议的“@”。
  • 是的,你当然是对的。我错过了他使用“@”的事实。
  • 你没有错过它 :) OP 已被编辑以包含您在评论中添加的代码。无时无刻不在发生。
【解决方案2】:

我认为这里的技巧是将数字作为数字而不是文本输入单元格。如果tr.Balance 是字符串,则可以使用 TryParse 将其转换为双精度:

object StringToDoubleIfPossible(string s)
{
    double parseResult;
    return !string.IsNullOrEmpty(s) && double.TryParse(s, out parseResult) ? (object)parseResult : s;
}

编辑: string.IsNullOrEmpty() 调用不是必需的。我把它放进去是因为我不确定 TryParse 是否可以处理空字符串。它可以。这样更好:

object StringToDoubleIfPossible(string s)
{
    double parseResult;
    return double.TryParse(s, out parseResult) ? (object)parseResult : s;
}

编辑:

呃!巴罗克是正确的。我想知道为什么这个数字首先作为文本输入。我应该更多地注意“@”格式。

【讨论】:

    【解决方案3】:

    您的代码ndcRange.NumberFormat = "@" 是首先将数字格式设置为文本的原因。在插入数据之前,只需将 @ 更改为适当的数字格式(例如 Kash 的答案中建议的格式)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-07
      • 1970-01-01
      相关资源
      最近更新 更多