我的问题是我在datagridview中有列日期,我希望它以excel格式显示到12个小时,因为它是24个小时(样本:16/06/19 7:00 PM),这个问题很好,我可以解决,但是真正的问题是,如果我的数据为null,它会像这样(16/06/19 12:00 AM)显示,它总是具有时间值12:00 AM,我只想显示的只是这样的日期(16/06 / 19)我需要一个条件,但是我不知道该如何帮助我,这是我导出到excel的代码:
Microsoft.Office.Interop.Excel._Application app = new
Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook =
app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
for (int i = 1; i < dataGridViewIn.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridViewIn.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridViewIn.Rows.Count - 1; i++)
{
(worksheet.Rows[i + 2 + ":" + i + 2, System.Reflection.Missing.Value] as Microsoft.Office.Interop.Excel.Range).NumberFormat = "@";
for (int j = 0; j < dataGridViewIn.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridViewIn.Rows[i].Cells[j].Value.ToString();
worksheet.Cells[i + 2, 3].NumberFormat = " m/d/yy h:mm AM/PM";
}
}
var saveFileDialoge = new SaveFileDialog();
saveFileDialoge.FileName = "TimeIn";
saveFileDialoge.DefaultExt = ".xlsx";
if (saveFileDialoge.ShowDialog() == DialogResult.OK)
{
workbook.SaveAs(saveFileDialoge.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
app.Visible = true;
}
答案 0 :(得分:1)
您希望12小时制使用小的hh
,而您希望24小时制使用大写的HH
if (dateTime == null)
{
DateTime date=Covert.ToDateTime( lastdate.ToString("dd/MM/yyyy hh:mm:ss.fff",CultureInfo.InvariantCulture));
}
在格式字符串中使用tt
来产生AM / PM指示符。
答案 1 :(得分:0)
Foreach (datagridview rw in this.datagridview1.rows){
For (int i=1 ; i<rw.cells.count ; i++){
if (rw.cells[i]. value == null){
rw.cells[i]. value = "*";
}
}
}