2016-11-04 42 views
2

我有一个使用DevExpress编辑的Excel文件,我正在使用NPOI进行读取。当我尝试获取日期单元格的值作为字符串时,它不保留原始值。如何获取包含日期的单元格的值并使用NPOI保留原始格式

例如: 在DevExpress网格中,我设置了此值:2016-08-12。我想在我的字符串中获得相同的值,但是我得到42689

我的代码来获取单元格的值是这样的:

ICell cell = row.GetCell(i); 
    cell.SetCellType(CellType.String); 
    string fieldString = cell.StringCellValue; 
    result = result + ";" + FieldValue; 

我怎样才能得到原始格式的日期值?

+0

请指定问题。 –

回答

3

在Excel中,日期存储为数字。如果你想得到格式化的日期,你需要检查单元格是否包含日期(有一个实用的方法),然后获取单元格的日期值,获取数据格式,最后将日期转换为字符串使用格式。您不应该强制CellType进行字符串操作,否则您将不能再通知单元格最初拥有日期。我建议做一个扩展方法类似这样的基于其类型,以获得格式化的单元格的值:

using NPOI.SS.UserModel; 
public static class NpoiExtensions 
{ 
    public static string GetFormattedCellValue(this ICell cell, IFormulaEvaluator eval = null) 
    { 
     if (cell != null) 
     { 
      switch (cell.CellType) 
      { 
       case CellType.String: 
        return cell.StringCellValue; 

       case CellType.Numeric: 
        if (DateUtil.IsCellDateFormatted(cell)) 
        { 
         DateTime date = cell.DateCellValue; 
         ICellStyle style = cell.CellStyle; 
         // Excel uses lowercase m for month whereas .Net uses uppercase 
         string format = style.GetDataFormatString().Replace('m', 'M'); 
         return date.ToString(format); 
        } 
        else 
        { 
         return cell.NumericCellValue.ToString(); 
        } 

       case CellType.Boolean: 
        return cell.BooleanCellValue ? "TRUE" : "FALSE"; 

       case CellType.Formula: 
        if (eval != null) 
         return GetFormattedCellValue(eval.EvaluateInCell(cell)); 
        else 
         return cell.CellFormula; 

       case CellType.Error: 
        return FormulaError.ForInt(cell.ErrorCellValue).String; 
      } 
     } 
     // null or blank cell, or unknown cell type 
     return string.Empty; 
    } 
} 

然后,使用这样的:

ICell cell = row.GetCell(i); 
string fieldString = cell.GetFormattedCellValue(); 
result = result + ";" + FieldValue; 

可选:如果您有任何公式来单元格,并且希望对这些公式进行评估,然后根据您的工作簿类型创建IFormulaEvaluator,并将评估器传递给GetFormattedCellValue()方法。例如:

IFormulaEvaluator eval; 
if (workbook is XSSFWorkbook) 
    eval = new XSSFFormulaEvaluator(workbook); 
else 
    eval = new HSSFFormulaEvaluator(workbook); 

... 

ICell cell = row.GetCell(i); 
string fieldString = cell.GetFormattedCellValue(eval); 
result = result + ";" + FieldValue; 
相关问题