【发布时间】:2010-05-06 02:36:59
【问题描述】:
是否可以确定 Excel 单元格的数据类型和格式?
我知道有.NumberFormat,但它返回的是格式而不是类型...
我需要知道它是否是自定义的,那么它应该返回自定义,货币应该返回货币等等。
【问题讨论】:
是否可以确定 Excel 单元格的数据类型和格式?
我知道有.NumberFormat,但它返回的是格式而不是类型...
我需要知道它是否是自定义的,那么它应该返回自定义,货币应该返回货币等等。
【问题讨论】:
在底层,Excel 以一种特殊的方式存储值(大多数数据类型实际上是双精度的),这使得在没有 Excel 帮助的情况下检测单元格格式变得很棘手。
因此,我建议您利用内置的 Excel CELL 函数,而不是自己询问数据类型:
private void button1_Click(object sender, EventArgs e)
{
//C1 is a cell I use to evaluate the Format of Cells A1 thru to A7
using (var rnEvaluate = xlApp.Range["C1:C1"].WithComCleanup())
{
for (int i = 1; i < 8; i++)
{
rnEvaluate.Resource.Value2 = "=CELL(\"format\",A" + i.ToString() + ")";
string cellFormat = GetExcelCellFormat(rnEvaluate.Resource.Value2);
System.Diagnostics.Debug.Write(cellFormat);
}
}
}
private string GetExcelCellFormat(string cellFormat = "G")
{
switch (cellFormat.Substring(0, 1))
{
case "F" :
return "Number";
break;
case "C":
return "Currency";
break;
case "D":
return "Date";
break;
default :
return "General";
break;
}
}
ps .WithComCleanup() 是因为我使用的是VSTO Contrib
【讨论】:
这取决于,如果它是一个 xslx 文件(Open XML excel),那么您可以解压缩 xlslx 文件(xlsx 是一个 zip 文件)并在 xl\worksheets\sheet{?}.xml 文件中检查该特定单元格.
不过,这可能是一种过于复杂的方法。
【讨论】:
<Data ss:Type="Number"> :(
从 Excel 范围中获取NumberFormat 后,您可以使用this table of formatting codes 或this reference from Microsoft 对其进行转换。请记住,如果自定义,则可以使用混合格式。
如果您只需要基本值(我在 Excel 2010 中的下拉菜单中的默认值):
我通过录制宏并修改所选单元格的数字格式来获得这些值。
编辑:
获得更多帮助以到达您想去的地方 - 假设您正在使用 Excel 互操作库(我知道如何访问 NumberFormat 函数的唯一方法):
string fileName = @"c:\Book1.xlsx";
Application app = new Application();
Workbook wb = app.Workbooks.Open(fileName,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Worksheet sheet = wb.Sheets[1]; //Change to the sheet you care about (1 based index)
var cell = sheet.Cells[1, 1]; //Change to the cell you care about (1 based index)
string cellNumberFormat = cell.NumberFormat; //Number format of cell to compare against known values
使用找到的互操作库的设置here。
【讨论】:
NumberFormat - 尽管单元格是货币、日期或其他格式,但它会吐出“一般”。链接也没有多大帮助。