Search code examples
c#epplus

C# formatting excel column with epplus as negative number with prentices


I am trying to get an column formatted as a number. I want it with 1000 separator and red prentices. I am using Epplus 5.7.5 and C# .net 4.72 Some reason it just ignores this formatting.

workSheet.Column(4).Style.Numberformat.Format = "#,##0 ;[Red](#,##0)";

Solution

  • I figured it out myself. The only issue with this is if you have a large amount of data formatting the individual cell will slow down the export.

    private static void CreateData(ExcelWorksheet workSheet, ref int rowIndex, DataTable dt)
        {
            int colIndex = 0;
            int intNumberCheck = 0;
    
            foreach (DataRow dr in dt.Rows) // Adding Data into rows
            {
                colIndex = 1;
                rowIndex++;
    
                foreach (DataColumn dc in dt.Columns)
                {
                    var cell = workSheet.Cells[rowIndex, colIndex];
    
                    bool isNumber = Int32.TryParse(dr[dc.ColumnName], out intNumberCheck);
    
                    if (isNumber == true)
                    {
                        //Setting Value in cell
                        
                        cell.Value = Convert.ToInt32(dr[dc.ColumnName]);
                        cell.Style.Numberformat.Format = "#,##0 ;[Red](#,##0)";
                        
                    }
                    else
                    {
                        //Setting Value in cell
                        cell.Value = Convert.ToString(dr[dc.ColumnName]).Trim();
                    }
    
                    colIndex++;
    
                }
            }
    
            dt.Dispose();
        }