我想将数据导出到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
答案 0 :(得分:1)
我建议您使用" Text"作为细胞类型。它将摆脱日期的自动格式更改。您可以使用以下代码:
xlWorkSheet.Cells[1, 1].NumberFormat = "@";