如何在将数据网格视图导出到excel时将日期转换为文本
本文关键字:excel 日期 转换 文本 数据 数据网 视图 网格 | 更新日期: 2023-09-27 18:21:56
将数据网格视图导出到excel时遇到问题。在数据网格视图中,有一列的日期为2014年5月12日。
当我使用这个代码导出它时
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();
它显示为2014年5月12日上午12:00
我不想那样。我希望它只是12/05/2014。我是怎么在for循环中做到这一点的,这就是我的意思??
我想检测单元格值是否为字符串将其转换为这种格式
供您参考,datagridview已经有了日期,格式是dd/MM/yyyy
该问题仅在导出时发生
有人知道怎么解决吗?
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;
}
帮助您;
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");
但我认为这应该被报告为将DateTime转换为指定格式的重复。
旁注:我还不能发表评论。