Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Currency format in Excel using C#

Tags:

I have a Model in C#

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

and from Database I receive the 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$.

I am using using 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.

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. 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";
like image 649
user0810 Avatar asked Nov 21 '18 16:11

user0810


1 Answers

Locale code for US dollar $ is [$$-en-US], and for Brazilian Real R$ is [$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.

like image 93
Slai Avatar answered Sep 19 '22 09:09

Slai