【问题标题】:How can i change the text format of a Excel Cell using C#?如何使用 C# 更改 Excel 单元格的文本格式?
【发布时间】:2012-05-23 13:02:23
【问题描述】:

我目前正在编写一个应用程序 (C#),以根据其他报告在 Excel 文件中生成报告。

问题是,一旦从某个工作表中获取一个数字,然后复制到另一个工作表,目标单元格的格式不正确,数字无法正确显示。

E.g : 
Number from source : 14.34 
Number on destination : 14.345661

如何格式化目标单元格以强制数字格式与源单元格相同。

谢谢!

【问题讨论】:

标签: c# excel


【解决方案1】:

excel中给定单元格/范围的格式可以通过代码设置。

public void SetCustomFormat(string format, int r, int c)
{
    ((Excel.Range)xlWks.Cells[r, c]).NumberFormat = format;
}

在您的具体情况下,我相信您需要使用“#.00”或“#.##”格式

【讨论】:

  • 看不到这个 xlWks 变量。这是工作表吗?
  • 是的,这就是工作表变量。我使用 xlWks 变量在我自己的代码内部定义了它。
【解决方案2】:

这是我使用的一些代码的 sn-p,向您展示格式化单元格的一般模式。显然,声明了一些变量,但它应该会告诉你你需要什么。

sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).Font.Bold = true;
sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).Interior.Color = Color.Silver.ToArgb();
sheet.get_Range("A" + CurrentRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
sheet.get_Range("A" + CompetencyStartRowIndex.ToString(), ColPrefix + CurrentRowIndex.ToString()).BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);

第一行,假设 CurrentRowIndex = 1 和 ColPrefix = "B",用结果值替换变量将转换为

sheet.get_Range("A1", "B1").Font.Bold = true;

无论如何,您都想设置数字格式。 (来了..)

sheet.Cells[Row, Column].NumberFormat = "0.00"

【讨论】:

  • 感谢您的帮助,但这不是我想要的。我正在寻找一种方法来格式化单元格内的文本,而不是单元格本身,如背景或字体格式。我希望以另一种方式解释文本
  • 我回答的最后一行似乎回答了您要查找的内容。也许我应该删除其余的,因为它是无关的。有时,当我应该简洁时,我愚蠢地试图完整。 ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
  • 1970-01-01
  • 2019-10-11
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
相关资源
最近更新 更多