Home » excel » c# – Apply format to many excel cells at once

c# – Apply format to many excel cells at once

Posted by: admin April 23, 2020 Leave a comment

Questions:

I would like to format all added values in my excel file and i have a “small” and “fast” solution like this:

Item2 is a List<string>, Item3 is a List<List<string>>

if (chkWithValues.Checked && results.Item3.Any())
{
    var rows = results.Item3.Count;
    var cols = results.Item3.Max(x => x.Count);
    object[,] values = new object[rows, cols];
    object[,] format = new object[rows, cols];

    //All returned items are inserted into the Excel file
    //Item2 contains the database types, Item3 the Values
    // pgMain shows the progress for the selected tables
    for (int j = 0; j < results.Item3.Count(); j++)
    {
        int tmpNbr = 1;

        foreach (string value in results.Item3[j])
        {
            values[j, tmpNbr - 1] = Converter.Convert(results.Item2[tmpNbr - 1], value).ToString().Replace("'", "");
            format[j, tmpNbr - 1] = ExcelColumnTypes.ConvertToExcelTypes(results.Item2[tmpNbr - 1]);
            tmpNbr++;
        }                            
        pgMain.Maximum = results.Item3.Count();
        pgMain.PerformStep();
    }
    Excel.Range range = xlWorksheet.Range["A3", GetExcelColumnName(cols) + (rows + 2)];
    range.Value = values;
    range.NumberFormat = format;
}

To add the numberformat efficiently with a single assignment, I’ve found a solution with a 2d array, which contains all number formats that should be set.

The problem is that I get the following error message "Unable to set the NumberFormat property of the Range class" when I have more than (i think) 50.000 cells to format.

Does someone know a solution that is fast and can handle a large amount of cells without error?

update:
ExcelColumnTypes.ConvertToExcelTypes

public static string ConvertToExcelTypes(string databaseType)
        {
            if (DatabaseColumnTypes.DOUBLE.Contains(databaseType))
                return DOUBLEPO1;
            if (DatabaseColumnTypes.DATE.Contains(databaseType))
                return DATE2;
            if (DatabaseColumnTypes.INTEGER.Contains(databaseType))
                return INT;
            return TEXT;
        }

The DatabaseColumnTypes are List with const or direct const.
Sample:

public const string VARBINARY = "varbinary";

 public static List<string> STRING = new List<string>()
        {
            CHAR,
            VARCHAR,
            TEXT,
            NTEXT,
            NCHAR,
            NVARCHAR,
            BINARY,
            VARBINARY
        };
How to&Answers:

Please change the

range.NumberFormat = format;

range.NumberFormatLocal = format;

Then it should work