如何在将datagridview导出为ex​​cel时将date转换为文本?

将数据网格视图导出为ex​​cel时遇到问题。 在datagridview中有12/5/2014的date列。

当我用这个代码导出它

Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); app.Visible = true; Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Add(1); Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1]; ws.Name = "Exported from gridview"; ws.Rows.HorizontalAlignment = HorizontalAlignment.Center; for (int i = 1; i < ExcelDGV.Columns.Count + 1; i++) { ws.Cells[1, i] = ExcelDGV.Columns[i - 1].HeaderText; } // storing Each row and column value to excel sheet for (int i = 0; i < ExcelDGV.Rows.Count - 1; i++) { for (int j = 0; j < ExcelDGV.Columns.Count; j++) { ws.Cells[i + 2, j + 1] = ExcelDGV.Rows[i].Cells[j].Value.ToString(); } } ws.Cells.EntireColumn.AutoFit(); wb.SaveAs("c:\\output.xls",Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive , Type.Missing, Type.Missing, Type.Missing, Type.Missing); app.Quit(); 

它显示了那样的12/05/2014 12:00 AM

我不希望它是这样的。 我想要它只是12/05/2014。 我怎么做,在for循环,这是我的意思?

我想检测如果单元格的值是string转换为这种格式

datagridview的date是这种格式dd / MM / yyyy

此问题仅在导出时发生

任何人都知道如何解决它?

为了帮助你;

 DateTime.ParseExact("12/02/21 12:00 AM", "yy/MM/dd HH:mm tt", System.Globalization.CultureInfo.InvariantCulture).ToString("MMM. dd, yyyy HH:mm:ss"); 

但我认为这应该被报告为转换date时间到指定的格式的副本。

旁注:我还不能评论。

  DateTime MyDate; if (!DateTime.TryParse(ExcelDGV.Rows[i].Cells[j].Value.ToString(), out MyDate)) { XcelApp.Cells[i + 2, j + 1] = ExcelDGV.Rows[i].Cells[j].Value.ToString(); } else { XcelApp.Cells[i + 2, j + 1] = MyDate; }