使用NPOI,如何返回已由Excel格式化的单元格值? [英] Using NPOI, how do I return a cell value as it has been formatted by Excel?

查看:601
本文介绍了使用NPOI,如何返回已由Excel格式化的单元格值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 NPOI ,可以将单元格值(尤其是数字值和日期值)格式化为它已经

Using NPOI, is there any buildin possibility to format a cell value (especially numeric and date values) as it has been formatted by Excel?

如果不是,最好的实施方法是什么?我想到了从Excel格式字符串到C#格式字符串的格式字符串转换器吗?

If not what would be the best way to implement it? I thought of a formatstring converter from Excel-formatstrings to C#-formatstrings?

以下示例假定Excel格式字符串和C#格式字符串相同.因此,它适用于一些基本格式字符串,例如:#,## 0.00"

The following example assumes the Excel-formatstring and the C#-formatstring are the same. So it works for some basic formatstrings like: "#,##0.00"

using NPOI.SS.UserModel;

ICell cell = workbook.GetSheet("table1").GetRow(0).GetCell(0);
string value = null;

if(cell.CellType == CellType.String) {
    value = cell.StringCellValue;
} else if(cell.CellType == CellType.Numeric) {
    string formatString = cell.CellStyle.GetDataFormatString();

    if(DateUtil.IsCellDateFormatted(cell)) {
        value = cell.DateCellValue.ToString(formatString);
    } else {
        value = cell.NumericCellValue.ToString(formatString);
    }
} else [...]

推荐答案

发现了内置的NPOI.但是,某些格式如"1983年9月18日,星期日" 的求值方式如"EEEE,1983年9月18日"..

Found the NPOI built in possibility. However some formats like "Sunday, September 18, 1983" are evaluated like "EEEE, September 18, 1983".

using NPOI.SS.UserModel;

DataFormatter dataFormatter = new DataFormatter(CultureInfo.CurrentCulture);
ICell cell = workbook.GetSheet("table1").GetRow(0).GetCell(0);

string value = dataFormatter.FormatCellValue(cell);

这篇关于使用NPOI,如何返回已由Excel格式化的单元格值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆