[英]C# Excel DateTime Export
我需要將一些數據導出到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;
嘗試像這樣將整個列格式化為日期列
range.EntireColumn.NumberFormat =“ DD / MM / YYYY”;
希望這會起作用
在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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.