在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;
請指定問題。 –