如何使用 C# 更改 Excel 单元格的文本格式
本文关键字:文本 格式 单元格 Excel 何使用 更改 | 更新日期: 2023-09-27 18:35:10
我目前正在编写一个应用程序(C#)来根据其他报告在excel文件中生成报告。
问题是,一旦从某个工作表中获取一个数字并复制到另一个工作表,目标单元格的格式不正确,并且该数字无法正确显示。
E.g :
Number from source : 14.34
Number on destination : 14.345661
如何格式化目标单元格以强制数字格式与源单元格相同。
谢谢!
excel中给定单元格/范围的格式可以通过代码设置。
public void SetCustomFormat(string format, int r, int c)
{
((Excel.Range)xlWks.Cells[r, c]).NumberFormat = format;
}
在您的特定情况下,我相信您需要使用"#.00"或"#.##"格式
这是我使用的一些代码的片段,向您展示格式化单元格的一般模式。 显然,声明了一些变量,但它应该显示您需要什么。
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"