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";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With