Ghazanfar Khan
Ghazanfar Khan

Reputation: 3718

Excel NumberFormat for on range not working using c#

I am trying to format currency column range using this format

NumberFormat = "$ #,##0.00";

Every time I get this result

£ 1,016.89

Here is the completed function for setting columns

public void SetColumns(List<ReportColumn> columns)
{
    try
    {
        int row = 9;
        int index = 10;
        int count = Report.Data.Count - 1;
        for (int i = 0; i < columns.Count; i++)
        {
            switch (columns[i].Type.ToUpperInvariant())
            {
                case ColumnSettingType.Number:
                    {
                        oRange = (Excel.Range)oSheet.Range[oSheet.Cells[index, i + 1], oSheet.Cells[index + count, i + 1]];
                        oRange.NumberFormat = "#,###,###0";
                        oRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;
                        break;
                    }
                case ColumnSettingType.Currency:
                    {
                        oRange = (Excel.Range)oSheet.Range[oSheet.Cells[index, i + 1], oSheet.Cells[index + count, i + 1]];
                        var format = "$ #,##0.00";
                        oRange.NumberFormat = format; 
                        oRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;
                        break;
                    }
                case ColumnSettingType.Percentage:
                    {
                        oRange = (Excel.Range)oSheet.Range[oSheet.Cells[index, i + 1], oSheet.Cells[index + count, i + 1]];
                        oRange.NumberFormat = "0.00%";
                        oRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;
                        break;
                    }
                case ColumnSettingType.Date:
                    {
                        oRange = (Excel.Range)oSheet.Range[oSheet.Cells[index, i + 1], oSheet.Cells[index + count, i + 1]];
                        oRange.NumberFormat = "MM/dd/yyyy";
                        oRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;
                        break;
                    }
            }
            oSheet.Cells[row, i + 1] = columns[i].ColumnName;
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Need help what I am doing wrong aur need to setup some culture with it.

Upvotes: 2

Views: 3519

Answers (1)

PaulF
PaulF

Reputation: 6773

It appears that the NumberFormat property uses the $ symbol to indicate the cell is in Currency format - that uses the current locale currency symbol as far as I can see.

The actual currency symbol used for the cell/range can be set in the NumberFormatLocal property.

Setting both should display the value as "$ 1,016.89"

 var format = "$ #,##0.00";
 oRange.NumberFormat = format;
 oRange.NumberFormatLocal = format;

Upvotes: 1

Related Questions