我的程序在Excel中創建輸出。Excel Interop單元格日期格式
一些日期似乎越來越誤解:
在打開該文件的日期,如屏幕截圖的混合物。
如果我實際上將光標放在Excel的計算框中(在screenprint中)並按回車,單元格的格式將恢復爲正確的格式。
我正在使用Microsoft.Office.Interop.Excel
將數據從Datatable
移至保存在我的解決方案中的Excel
模板。
之前將數據放入細胞我改變各列的NumberFormat相應使用switch
:
for(int i = 1; i < NumColumns + 1; i++) {
switch(dt.Columns[i-1].DataType.ToString()) {
case "System.Int32":
xlWorkSheet.Columns[i].NumberFormat = "#,##0_ ;[Red]-#,##0 ";
break;
case "System.String":
xlWorkSheet.Columns[i].NumberFormat = "@";
break;
case "System.DateTime":
xlWorkSheet.Columns[i].NumberFormat = "[$-809]dd mmmm yyyy;@"; //"dd-mmm-yy";
break;
case "System.Date":
xlWorkSheet.Columns[i].NumberFormat = "[$-809]dd mmmm yyyy;@"; //"dd-mmm-yy";
break;
default:
xlWorkSheet.Columns[i].NumberFormat = "@";
break;
}
}
要移動從數據表中的值我使用嵌套循環:
//move header totals into the spreadsheet
for(int i = 1; i < NumColumns + 1; i++) {
xlWorkSheet.Cells[1, i].value = dt.Columns[i - 1].ColumnName;
}
//move in the data
DataView dv = new DataView(dt);
dv.Sort = "Date ASC";
int rowCount = 2;
string theValue;
try {
foreach(DataRowView dr in dv) {//(DataRow dr indt.Rows)
for(int i = 1; i < NumColumns + 1; i++) {
theValue = dr[i - 1].ToString();
xlWorkSheet.Cells[rowCount, i].value = theValue;
}
rowCount += 1;
}
} catch(Exception) {
throw;
}
在存儲當我填充數據表我試着用DATETIME
和以下內容明確地說明了類型:
SELECT
"Date" = CONVERT(DATE,b.[Date])
...
如何使我的日期數據如此明確以至Excel無法曲解並且應用所有所需的格式?
編輯
下一頁(未經測試)在嵌套循環嘗試如下:
int rowCount = 2;
string theValue;
DateTime dtm;
DateTime d;
try {
foreach(DataRowView dr in dv) {//(DataRow dr indt.Rows)
for(int i = 1; i < NumColumns + 1; i++) {
//theValue = dr[i - 1].ToString();
//xlWorkSheet.Cells[rowCount, i].value = theValue;
switch(dr[i - 1].GetType().ToString()) {
case "System.DateTime":
dtm = Convert.ToDateTime(dr[i - 1]);
xlWorkSheet.Cells[rowCount, i].value = dtm.ToOADate();
break;
case "System.Date":
d = Convert.ToDateTime(dr[i - 1]);
xlWorkSheet.Cells[rowCount, i].value = d.ToOADate();
break;
default:
theValue = dr[i - 1].ToString();
xlWorkSheet.Cells[rowCount, i].value = theValue;
break;
}
}
rowCount += 1;
}
} catch(Exception) {
throw;
}
... + 1個感謝如果它的日期時間使用'ToOADate()';如果它的字符串,然後使用'ToString()'等? – whytheq 2013-03-25 09:19:11
是的,這將工作。另外,我認爲'DataRow'索引器(例如'dr [i-1]')將根據列類型爲您打字。所以你應該能夠測試返回對象(例如'if(value is DateTime)'並且調用'ToOADate()'。 – 2013-03-25 13:06:21
...好的 - 我將用新的嵌套循環編輯我的OP - 我還沒有測試過,我在黑暗中感覺有點;所以不要笑! – whytheq 2013-03-25 13:38:10