将数据写入Excel时如何制作正确的日期格式

cod*_*nix 35 .net c# excel office-interop

我使用office interop将DataTable导出到Excel文件.问题是,Excel不会识别日期,而是显示数字.在另一种情况下,我传递一个字符串,然后将其识别为日期.在这两种情况下,数据都搞砸了.

我尝试过NumberFormat @,它应该以文本格式存储单元格,但它也不起作用.

Application app = new Application();
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
app.EnableAnimations = false;
app.EnableAutoComplete = false;
app.EnableSound = false;
app.EnableTipWizard = false;
app.ErrorCheckingOptions.BackgroundChecking = false; 

Workbook wb = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws = (Worksheet)wb.Worksheets[1];

for (int j = 0; j < dt.Rows.Count; j++)
{
    for (int i = 0; i < dt.Columns.Count; i++)
    {
        Range rng = ws.Cells[j+2, i+1]as Range;
        rng.Value2 = dt.Rows[j][i].ToString();
        rng.NumberFormat = "@";
    }   
}           

wb.SaveAs(filename, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
       Missing.Value, XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

wb.Close(false, Missing.Value, Missing.Value);            

app.Workbooks.Close();
app.Application.Quit();
app.Quit();    
System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
ws = null;
wb = null;
app = null;
GC.Collect();
Run Code Online (Sandbox Code Playgroud)

为什么我的NumberFormat @不起作用?Textformat不应该显示与我输入的相同的所有内容吗?

dcp*_*dcp 36

您是否尝试将整个列格式化为日期列?像这样的东西:

Range rg = (Excel.Range)worksheetobject.Cells[1,1];
rg.EntireColumn.NumberFormat = "MM/DD/YYYY";
Run Code Online (Sandbox Code Playgroud)

您可以尝试的另一件事是在将文本加载到Excel单元格之前在字符串表达式之前放置一个勾号(不确定是否重要,但是在直接在单元格中键入文本时它可以正常工作).


Ass*_*saf 10

尝试使用

DateTime.ToOADate()
Run Code Online (Sandbox Code Playgroud)

并将其作为单元格的双倍.Mac系统上的Excel可能会出现问题(它使用不同的日期时间 - >双转换),但它适用于大多数情况.

希望这可以帮助.


Ver*_*ile 6

这对我有用:

sheet.Cells[currentRow, ++currentColumn] = "'" + theDate.ToString("MM/dd/yy");
Run Code Online (Sandbox Code Playgroud)

请注意在日期之前添加的刻度线。