我需要将一些数据导出到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;
答案 0 :(得分:1)
尝试将整列格式化为日期列,如下所示
range.EntireColumn.NumberFormat =“DD / MM / YYYY”;
希望这会起作用
答案 1 :(得分:0)
有了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;