时间值未在我的Excel工作表中正确反映

时间:2014-05-28 08:08:44

标签: c# excel-vba vba excel

我设法创建了一个Excel文件,并尝试将当前系统时序更新为工作表的第一个单元格。但是当创建文件时,我得到错误的时间值。我想要当前的系统时间,但它显示的是12:00:00但日期正确显示。

我正在使用Microsoft Excel 12.0对象库。我需要帮助来获取当前系统时序或需要根据日期时间选择器反映时间。 这是我的代码:

namespace Test6attendance
{
    public partial class Form1 : Form
    {
       public Form1()
       {
           InitializeComponent();
       }

       private void button1_Click(object sender, EventArgs e)
       {
           Excel.Application xlApp;
           Excel.Workbook xlWorkBook;
           Excel.Worksheet xlWorkSheet;
           object misValue = System.Reflection.Missing.Value;
           xlApp = new Excel.Application();
           xlWorkBook = xlApp.Workbooks.Add(misValue);
           xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
           xlWorkSheet.Cells[1, 1] = DateTime.Now.Date.ToString("MM/dd/ yyyy, hh:mm:ss tt");                        

           xlWorkBook.SaveAs("D:\\login.xlscsharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue,      misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
           xlWorkBook.Close(true, misValue, misValue);
           xlApp.Quit();
           releaseObject(xlWorkSheet);
           releaseObject(xlWorkBook);
           releaseObject(xlApp);                                 
           MessageBox.Show("Excel file created , you can find the file D:\\csharp-Excel.xls");
       }

       private void releaseObject(object obj)
       {       
           try
           {
               System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
               obj = null;
           }
           catch (Exception ex)
           {
               obj = null;
               MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
           }
           finally
           {
               GC.Collect();
           }
       }
    }    
}

1 个答案:

答案 0 :(得分:4)

这是因为以下几行:

xlWorkSheet.Cells[1, 1] = DateTime.Now.Date.ToString("MM/dd/ yyyy, hh:mm:ss tt");

DateTime.Now.Date会将time属性设置为Midnight。使用此替代

xlWorkSheet.Cells[1, 1] = DateTime.Now.ToString("MM/dd/ yyyy, hh:mm:ss tt");

以下是DateTime.Now PropertyDateTime.Date Property