将日期时间导出到 excel
export datetime to excel
我想将数据导出到 windows 表单应用程序中的 excel 文件,但是当我尝试导出日期时,格式发生了变化。我想使用格式 dd-MM-yyyy
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("Excel is not properly installed!!");
return;
}
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1].NumberFormat = "dd/mm/yyyy";
xlWorkSheet.Cells[1, 1] = "19-02-2015";
xlWorkSheet.Cells[2, 1] = "02-03-2015";
xlWorkSheet.Cells[2, 1].NumberFormat = "dd/mm/yyyy";
xlWorkBook.SaveAs("C:\Users\user\Desktop\Data.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
excel 文件中的结果是:
19-2-2015 作为文本
02/03/2015 作为日期时间
我用 excel 2013
那么如何将 12 日以上的日期导出到 excel 并给它们格式 mm/dd/jjjj
我建议您使用 "Text" 作为细胞类型。它将摆脱日期的自动格式更改。您可以使用以下代码:
xlWorkSheet.Cells[1, 1].NumberFormat = "@";
我想将数据导出到 windows 表单应用程序中的 excel 文件,但是当我尝试导出日期时,格式发生了变化。我想使用格式 dd-MM-yyyy
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("Excel is not properly installed!!");
return;
}
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1].NumberFormat = "dd/mm/yyyy";
xlWorkSheet.Cells[1, 1] = "19-02-2015";
xlWorkSheet.Cells[2, 1] = "02-03-2015";
xlWorkSheet.Cells[2, 1].NumberFormat = "dd/mm/yyyy";
xlWorkBook.SaveAs("C:\Users\user\Desktop\Data.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
excel 文件中的结果是: 19-2-2015 作为文本 02/03/2015 作为日期时间 我用 excel 2013
那么如何将 12 日以上的日期导出到 excel 并给它们格式 mm/dd/jjjj
我建议您使用 "Text" 作为细胞类型。它将摆脱日期的自动格式更改。您可以使用以下代码:
xlWorkSheet.Cells[1, 1].NumberFormat = "@";