繁体   English   中英

在 c# 中使用 Microsoft.Office.Interop.Excel 在 excel 列中设置数字、文本和日期等数据类型

[英]Set data type like number, text and date in excel column using Microsoft.Office.Interop.Excel in c#

我正在尝试将数据类型设置为 C# 中的 excel 列,在本例中为数字、文本和日期。

如何为整个 excel 列设置格式?

将范围设置为文本:

xlYourRange.NumberFormat = "@";

您还可以使用撇号为您放入单元格的值添加前缀,以便将其格式化为文本:

xlYourRange.Value = "'0123456";

将范围设置为数字

xlYourRange.NumberFormat = "0";

显然,如果您想为整个列设置格式,那么您的范围将是该列。

xlYourRange = xlWorksheet.get_Range("A1").EntireColumn;

编辑:

日期有点复杂,还取决于您的区域设置:

// Results in a Date field of "23/5/2011"

xlRange.NumberFormat = "DD/MM/YYYY";
xlRange.Value = "23/5/2011";

// Results in a Custom field of "23/5/2011"

xlRange.NumberFormat = "DD-MM-YYYY";
xlRange.Value = "23/5/2011";

// Results in a Custom field of "05/23/2011"

xlRange.NumberFormat = "MM/DD/YYYY";
xlRange.Value = "5/23/2011";

// Results in a Custom field of "05-23-2011"

xlRange.NumberFormat = "MM-DD-YYYY";
xlRange.Value = "5/23/2011";

// Results in a Date field of "23/05/2011"

xlRange.NumberFormat = "DD/MM/YYYY";
xlRange.Value = "5/23/2011";

// Results in a Custom field of "23-05-2011"

xlRange.NumberFormat = "DD-MM-YYYY";
xlRange.Value = "5/23/2011";

// Results in a Custom field of "23/5/2011"

xlRange.NumberFormat = "MM/DD/YYYY";
xlRange.Value = "23/5/2011";

// Results in a Custom field of "23/5/2011"

xlRange.NumberFormat = "MM-DD-YYYY";
xlRange.Value = "23/5/2011";

是的,使用日期格式,一切都变得更加复杂——甚至比Sid Holland提到的还要复杂。 原因在于一些本地化问题。 例如,如果你的Windows系统有俄语本地化,你应该在日期格式中使用俄语字母,如“ДД.MM.ГГГГ”或“ГГГГ-MM-ДД”,因此,你应该能够提取和应用这些字母。 在此处查看或多或少完整的描述和解决方案: https : //stackoverflow.com/a/35418176/2199512

在值的开头连接一个撇号解决我的问题:

row["Total Sold\/Off"] = "'" + row["Sold"].ToString() + "\/" + row["Offered"].ToString();

前段时间我在这个问题上提出了一个问题的答案。

最值得注意的是,这个人在他的回答中使用的数据类型是:

private struct ExcelDataTypes
{
    public const string NUMBER = "NUMBER";
    public const string DATETIME = "DATETIME";
    public const string TEXT = "TEXT"; // also works with "STRING".
}

看起来熟悉?

如果你有兴趣,这里是链接:

使用 Microsoft Access 数据库引擎通过 OleDb 将数据表插入 Excel

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM