1

I am creating an Excel file using NPOI.

I declare the sheet this way:

        var workbook = new XSSFWorkbook();
        var sheet = workbook.CreateSheet(title);

The Excel is populated with data. The relevant part is when I set a date & time value:

                        if (data is DateTime)
                        {
                            cell.CellStyle = GetDateTimeStyle(workbook, true, GetCustomFormatForColumn(column));
                            cell.SetCellValue(Convert.ToDateTime(data));
                        }

where cell is ICell cell = row.CreateCell(column); and GetDateTimeStyle method is:

    private ICellStyle GetDateTimeStyle(XSSFWorkbook wb, bool useBorder, string customFormat)
    {
        if (!_styles.TryGetValue("DATETIME", out ICellStyle style))
        {
            style = wb.CreateCellStyle();
            style.SetFont(GetItemFont(wb));

            style.Alignment = HorizontalAlignment.Center;

            if (useBorder)
                SetBorder(style);

            if (!String.IsNullOrEmpty(customFormat))
                style.DataFormat = wb.CreateDataFormat().GetFormat(customFormat);
            else
                style.DataFormat = wb.CreateDataFormat().GetFormat("dd/MM/yyyy HH:mm:ss");

            _styles.Add("DATETIME", style);
        }

        return style;
    }

After all cells are populated, I run this for loop:

        column = 0;
        foreach (string header in columnNames)
            sheet.AutoSizeColumn(column++);

After that, resulting Excel has all columns autosized but column that contains the date and time values.

The cells containing date and time values are expanded in width but there are some pixels left to be expanded in order to display the whole date and time instead of just #########.

Is there a way to solve that?

Regards Jaime

jstuardo
  • 3,901
  • 14
  • 61
  • 136

0 Answers0