C# 获取Excel日期数据并与现在时间比较

Excel表中数据:

C# 获取Excel日期数据并与现在时间比较

 

读取Excel中D1中的数据:

        DateTime timeNow1 = DateTime.Now;//获取现在时间
            DateTime timeNow2;//比较时间

            //timediff(timenow1, timenow2, "h");

            //读取Excel数据
            Excel.Application xapp = new Excel.Application();
            string filepath = txt_Excel.Text;
            Excel.Workbook xbook = xapp.Workbooks._Open(filepath, Missing.Value, Missing.Value,
                                    Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                                    Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

            Excel.Worksheet xsheet = (Excel.Worksheet)xbook.Sheets[1];

            xapp.DisplayAlerts = false;

            timeNow2 = xsheet.Cells[1, 4].Value;//获取xsheet中D1数据
       
       ...//关闭Excel应用和进程

时间差函数:(摘自百度经验:http://jingyan.baidu.com/article/a378c96072cf76b328283006.html

private int TimeDiff(DateTime dt1,DateTime dt2,string flag)
        {
            double yearLen = 365;//年的长度,365天
            double monthLen = (365 / 12);//每个月平均的天数

            TimeSpan ts1 = new TimeSpan(dt1.Ticks);
            TimeSpan ts2 = new TimeSpan(dt2.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();

            switch(flag)
            {
                case"y"://返回两个日期的年份间隔
                    return Convert.ToInt32(ts.Days / yearLen);
                case"M"://返回两个日期的月份间隔
                    return Convert.ToInt32(ts.Days / monthLen);
                case"d"://返回两个日期的天数间隔
                    return ts.Days;
                case"h"://返回两个日期的小时间隔
                    return ts.Hours;
                case"m"://返回两个日期的分钟间隔
                    return ts.Minutes;
                case"s"://返回日期的秒钟间隔
                    return ts.Seconds;
                case"ms"://返回两个时间的微妙间隔
                    return ts.Milliseconds;
                default:
                    return 0;
            }
        }

再调用此时间差函数输出两个时间的小时差的绝对值:

MessageBox.Show("两个时间相差" + TimeDiff(timeNow1, timeNow2, "h").ToString() + "小时。");

最后退出Excel,并结束Excel进程,防止程序占用进程导致的Excel表格变成只读状态:(摘自百度经验:http://jingyan.baidu.com/article/ab69b270be4b2f2ca6189f5d.html

//引用
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

在程序中添加代码:

public partial class Form1 : Form
{
  //引用
  [DllImport("User32.dll", CharSet = CharSet.Auto)]
  public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);

  public Form1()
    {
      InitializeComponent();
    }

  ....

}

在获取Excel数据下关闭Excel应用和进程:

        xapp.Quit();//退出内存

            //杀死进程
            IntPtr t = new IntPtr(xapp.Hwnd);
            int k = 0;
            GetWindowThreadProcessId(t, out k);
            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
            p.Kill();

            MessageBox.Show("Write Success");

C# 获取Excel日期数据并与现在时间比较 

 

其中有不足之处望大神提醒~