如果我在datagridview中导出的时间为null,那么当我导出它的时间为12:00时,我不知道如何在导出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)
仅在有要写入的数据时,才添加检查并写入excel单元格。
for (int j = 0; j < dataGridViewIn.Columns.Count; j++)
{
if (dataGridViewIn.Rows[i].Cells[j].Value != null)
{
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";
}
}