2016-11-04 211 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; 
相關問題