2013-02-27 83 views
0

我使用NPOI导出了。
我设置单元格的值:
NPOI导出日期时间问题

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

现在,EXCELL认为这是一个文本字段,我需要一套细胞类型赛过DateTime
这可能吗?
我曾尝试:

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

,但不起作用。

回答

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; 
    } 
}