我该如何出口日期?

时间:2015-03-30 08:18:49

标签: c# excel winforms datagrid

 Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
        Workbook wb = Excel.Workbooks.Add(XlSheetType.xlWorksheet);
        Worksheet ws = (Worksheet)Excel.ActiveSheet;
        Excel.Visible = true;

        ws.Cells[1, 1] = "Tarih";
        ws.Cells[1, 2] = "Kasiyer";
        ws.Cells[1, 3] = "Ucret";
        ws.Cells[1, 4] = "Bilet No";
        ws.Cells[1, 5] = "Firma Adı";
        for (int j = 2; j < dataGridView1.Rows.Count; j++)
        {
            for (int i = 2; i <= 5; i++)
            {
                ws.Cells[j,i]=dataGridView1.Rows[j-2].Cells[i-1].Value;
            }
        }

日期不会进入Excel中的First Cell。我怎样才能做到这一点 ?请帮我 ?而且我收到了一条警告,如“HRESULTözeldurumöndürdü:0x800AC472”

1 个答案:

答案 0 :(得分:0)

你不可能采用日期值,它返回null并给出错误。只为日期列,您尝试转换。

for (int i = 1; i < dataGridView1.Rows.Count; i++)
    {
        ws.Cells[i,0] = (Convert.ToDateTime(ws.Cells[i,0]).ToOADate();
    }

另外你也可以试试。

Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
range = range.get_Resize(rowCount, columnCount);
range.EntireColumn.NumberFormat = "DD/MM/YYYY";