NPOI导出日期时间问题
本文关键字:时间 问题 日期 NPOI | 更新日期: 2023-09-27 18:01:18
我用NPOI做了出口。
设置单元格值:
row.CreateCell(6).SetCellValue("This is date string");
现在,excel将其视为文本字段,我需要excel将单元格类型设置为DateTime
。
这可能吗?
我试过了:
row.CreateCell(6).SetCellValue(DateTime.Parse("This is date string"));
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;
}
}