我需要将一些数据导出到Excel工作表。数据由数据时间值和读数组成。我的问题是,当我导出日期时间值时,它们将其格式更改为美国日期而不是英国日期。
我尝试通过将格式添加到日期时间值所在的范围来对其进行排序,现在它变得更加有趣。我注意到,直到9个月,它都在正确处理英国格式的日期时间值,但在那之后,它会更改为美国格式。
打开excel文件后,我通过应用程序在单元格上插入的格式仅应用于美国格式。
请看我的代码,它可能会帮助解决我的问题:
// Get dimensions of the 2-d array
int rowCount = data2.GetLength(0);
int columnCount = data2.GetLength(1);
// Get an Excel Range of the same dimensions
Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
range = range.get_Resize(rowCount, columnCount);
// Assign the 2-d array to the Excel Range
range.set_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault, data2);
// Reset the range
range = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
range = range.get_Resize(rowCount, 1);
// Set the format type of the range
range.NumberFormat = "DD/MMM/YYYY hh:mm:ss";
使用adrianm帮助编辑解决方案以下是解决方案代码:
我保留了之前包含的代码不变,但我更改了创建data2对象数组( object,data2)的代码。
//create the empty array
var result = new object[data.Count, data[0].Count];
//insert all of the values in it
for (int i = 0; i < data.Count; i++)
{
for (int j = 0; j < data[i].Count; j++)
{
if (j < data[i].Count)
result[i, j] = data[i][j];
else
result[i, j] = " ";
}
}
//change the date time values to doubles which are
//in the first column after the first entry
for (int i = 1; i < data.Count; i++)
{
result[i, 0] = (Convert.ToDateTime(result[i, 0])).ToOADate();
}
return result;
发布于 2014-05-30 16:09:18
有了adrianm的帮助,下面是解决方案代码:
我保留了之前包含的代码不变,但我更改了创建data2对象数组( object,data2)的代码。
//create the empty array
var result = new object[data.Count, data[0].Count];
//insert all of the values in it
for (int i = 0; i < data.Count; i++)
{
for (int j = 0; j < data[i].Count; j++)
{
if (j < data[i].Count)
result[i, j] = data[i][j];
else
result[i, j] = " ";
}
}
//change the date time values to doubles which are
//in the first column after the first entry
for (int i = 1; i < data.Count; i++)
{
result[i, 0] = (Convert.ToDateTime(result[i, 0])).ToOADate();
}
return result;
发布于 2013-10-09 19:25:42
尝试将整个列的格式设置为日期列,如下所示
range.EntireColumn.NumberFormat =“日/月/年”;
希望这能行得通
https://stackoverflow.com/questions/19269851
复制相似问题