简体   繁体   English

使用 C# 在 Excel 中设置货币格式

[英]Set Currency format in Excel using C#

I have a Model in C#我有一个 C# 模型

    public class Model
    {
        public int CurrencyId{ get; set; }
        public decimal? ValueMoney{ get; set; }
    }

and from Database I receive the List<Model>并从数据库我收到List<Model>

I want to write the ValueMoneys in Excel Worksheet in Currency format and depending on CurrencyId it has to be US dollar $ or Brazilian Real R$.我想在 Excel 工作表中以货币格式编写 ValueMoneys,根据 CurrencyId,它必须是美元 $ 或巴西雷亚尔 R$。

I am using using Microsoft.Office.Interop.Excel;我正在使用Microsoft.Office.Interop.Excel;

My code look like this:我的代码如下所示:

var data = GetValues().ToList();
Application xlApp = new Application();
Workbook xlWorkBook = null;
Worksheet xlWorkSheet = xlWorkBook.Worksheets[1];

for (int i = 1; i < data.count; i++){
     xlWorkSheet.Cells[i, 1] = data[i].ValueMoney!= null ? data[i].CurrencyId == 2 ? data[i].ValueMoney.Value.ToString("C", new CultureInfo("pt-BR")) : data[i].ValueMoney.Value.ToString("C", new CultureInfo("en-US")) : "";       
    ((Range)xlWorkSheet.Cells[i, 1]).Style = "Currency" ;
}

The problem is that in Excel it shows me the warning that it is a string and ask to change to number format.问题是在 Excel 中,它向我显示了它是一个字符串并要求更改为数字格式的警告。

I was trying to use我试图使用

xlWorkSheet.Cells[i, 1] = data[i].ValueMoney
((Range)xlWorkSheet.Cells[i, 1]).NumberFormat = "$ #,##0.00" 

but it always shows R$ since I am in Brazil.但自从我在巴西以来,它总是显示 R$。 Thank you for help in advance.提前感谢您的帮助。

[UPDATE] It works [更新] 它有效

xlWorkSheet.Cells[i, 1] = data[i].ValueMoney;
((Range)xlWorkSheet.Cells[i, 1]).NumberFormat = data[i].CurrencyId == 2 ? "$ #,##0.00" : "[$$-409] #,##0.00";

Locale code for US dollar $ is [$$-en-US] , and for Brazilian Real R$ is [$R$-pt-BR] .美元 $ 的区域设置代码是[$$-en-US] ,巴西雷亚尔 R$ 的区域设置代码是[$R$-pt-BR] For example :例如 :

.NumberFormat = "[$$-en-US] #,##0.00";

The locale codes can be found by setting the Symbol in the Currency section of the Excel Format Cells dialog, and then checking the corresponding number format in the Custom section of the same dialog.通过在 Excel 格式单元格对话框的货币部分中设置符号,然后在同一对话框的自定义部分中检查相应的数字格式,可以找到区域设置代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM