NPOI DataFormat

Estoy exportando una cuadrícula con NPOI v1.2.3 y tengo problemas para que funcione el formato de celda.

Tengo una clase que exporta una lista de objetos a un archivo XLS. Se crea una fila para cada objeto y se agrega una celda para cada propiedad configurada. El formato de datos de la celda se puede establecer en un nivel por propiedad.

He leido esono deberías crear un nuevo estilo para cada celda. No puedo codificar mis estilos, ya que mi exportador necesita admitir cualquier clase. En cambio, escribí un pequeño sistema de caché que solo crea un nuevo CellStyle si aún no se ha creado uno para el formato actual de la celda.

Desafortunadamente, esto aún no ha resuelto el problema. El formato no se aplica correctamente en el archivo XLS final. En mi caso de prueba, la mayoría de las celdas en el XLS están usando el formato "Fecha", aunque solo unas pocas columnas son fechas. Sin embargo, la primera columna usa correctamente un formato personalizado. No hay celdas configuradas en texto, aunque esa debería ser la mayoría de ellas.

¿Qué estoy haciendo mal?

Código

El siguiente método "AddRecords" se utiliza para agregar las filas de datos (las filas de encabezado y pie de página se agregan por separado). El último bit de código es el método que carga perezosamente CellStyles.

private void AddRecords( Sheet sheet, IList<T> records )
{
    foreach( var record in records )
    {
        // append row
        var row = sheet.CreateRow ( sheet.LastRowNum + 1 );

        // iterate through all configured columns
        foreach ( var column in GetColumns() )
        {
            // append cell
            Cell cell = row.CreateCell ( row.LastCellNum == -1 ? 0 : row.LastCellNum );

            // get the property value of the column from the record
            object value = GetCellValue ( column, record );

            // extension method that takes an object value and calls the appropriate type-specific SetCellValue overload
            cell.SetCellValue ( value );

            // get format from the column definition ("m/d", "##.###", etc.), or use the default
            string dataFormat = column.DataFormat ?? GetDefaultDataFormat ( value );

            // find/create cell style
            cell.CellStyle = GetCellStyleForFormat( sheet.Workbook, dataFormat );
        }
    }
}

/// <summary>
/// Returns a default format string based on the object type of value.
///
/// http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/BuiltinFormats.html
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private string GetDefaultDataFormat( object value )
{
    if( value == null )
    {
        return "General";
    }

    if( value is DateTime )
    {
        return "m/d";
    }

    if( value is bool )
    {
        return "[=0]\"Yes\";[=1]\"No\"";
    }

    if( value is byte || value is ushort || value is short ||
         value is uint || value is int || value is ulong || value is long )
    {
        return "0";
    }

    if( value is float || value is double )
    {
        return "0.00";
    }

    // strings and anything else should be text
    return "text";
}

private readonly Dictionary<string, CellStyle> _cellStyleCache = new Dictionary < string, CellStyle > ();

private CellStyle GetCellStyleForFormat( Workbook workbook, string dataFormat )
{
    if( !_cellStyleCache.ContainsKey ( dataFormat ) )
    {
        var newDataFormat = workbook.CreateDataFormat ();
        var style = workbook.CreateCellStyle ();
        style.DataFormat = newDataFormat.GetFormat ( dataFormat );

        _cellStyleCache[dataFormat] = style;
    }

    return _cellStyleCache[dataFormat];
}

Respuestas a la pregunta(1)

Su respuesta a la pregunta