是否有可能弄清楚Excel格式的格式我知道有.NumberFormat但它返回格式但不是类型...基本上我需要知道它是否是自定义然后它应该返回自定义,如果它是货币应返回货币或任何其他数据类型 请帮帮我
答案 0 :(得分:3)
引擎盖下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
答案 1 :(得分:0)
这取决于,如果它是一个xslx文件(Open XML excel),那么你可以解压缩xlslx文件(xlsx是一个zip文件)并检查xl \ worksheets \ sheet {?}。xml文件中的特定单元格
这可能是一种过于复杂的方式。
答案 2 :(得分:0)
从Excel范围获取NumberFormat
后,您可以使用this table of formatting codes或this reference from Microsoft进行转换。请记住,如果定制,可以使用混合格式。
如果您只想要基本值(我的默认值来自Excel 2010中的下拉列表):
我通过录制宏并修改所选单元格的数字格式来获取这些值。
修改强>
如果您正在使用Excel互操作库(我知道如何访问NumberFormat
函数的唯一方法),那么可以获得更多帮助 - 假设您正在使用Excel互操作库:
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。