0

我使用 NPOI 进行了导出。
我设置单元格值:

row.CreateCell(6).SetCellValue("This is date string");

现在,excel 将此视为一个文本字段,我需要将单元格类型设置为DateTime.
这可能吗?
我努力了:

row.CreateCell(6).SetCellValue(DateTime.Parse("This is date string"));

但不起作用。

4

1 回答 1

2
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 );

            object value = GetCellValue ( column, record );
            cell.SetCellValue ( value );
            string dataFormat = column.DataFormat ??"m/d";
            cell.CellStyle = GetCellStyleForFormat( sheet.Workbook, dataFormat );
        }
    }
}

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

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

        // check if this is a built-in format
        var builtinFormatId = HSSFDataFormat.GetBuiltinFormat ( dataFormat );

        if( builtinFormatId != - 1)
        {
            style.DataFormat = builtinFormatId;
        }
        else
        {
            // not a built-in format, so create a new one
            var newDataFormat = workbook.CreateDataFormat ();
            style.DataFormat = newDataFormat.GetFormat ( dataFormat );
        }

        _cellStyleCache[dataFormat] = style;
    }
}
于 2013-02-27T12:28:29.443 回答