如何在c#中观察excel文件的变化

本文关键字:excel 文件 变化 观察 | 更新日期: 2023-09-27 18:10:53

我正在开发监视文件更改,显示通知并将更改列表插入listview。我有困难,想要只更改通知,如果更改excel文件的属性。现在如果改变excel属性,显示创建,删除,重命名通知。谁能给我建议一下吗?

代码:

string filepath = C:'New Folder;
private void watcher_Changed(object sender, FileSystemEventArgs e)
    {
        sfilepath = e.FullPath.Substring(0, e.FullPath.Length - e.Name.Length - 1);
        if (sfilepath == filepath)
        {
            FileInfo fileInfo = new FileInfo(e.FullPath);
            DateTime lastWriteTime = fileInfo.LastWriteTime;
            DateTime nowdt = DateTime.Now;
            if (lastWriteTime == nowdt)
            {                    
                this.notifyIcon1.ShowBalloonTip(1, "File " + e.ChangeType, e.FullPath, ToolTipIcon.Info);                                        
            }
        }
    }
    private void watcher_Created(object sender, FileSystemEventArgs e)
    {
        sfilepath = e.FullPath.Substring(0, e.FullPath.Length - e.Name.Length - 1);
        if (sfilepath == filepath)
        {
            this.notifyIcon1.ShowBalloonTip(1, "File " + e.ChangeType, e.FullPath, ToolTipIcon.Info);                                
        }
    }
    private void watcher_Deleted(object sender, FileSystemEventArgs e)
    {
        sfilepath = e.FullPath.Substring(0, e.FullPath.Length - e.Name.Length - 1);
        if (sfilepath == filepath)
        {
            this.notifyIcon1.ShowBalloonTip(1, "File " + e.ChangeType, e.FullPath, ToolTipIcon.Info);                               
        }
    }
    private void watcher_Renamed(object sender, RenamedEventArgs e)
    {
        sfilepath = e.FullPath.Substring(0, e.FullPath.Length - e.Name.Length - 1);
        if (sfilepath == filepath)
        {
            this.notifyIcon1.ShowBalloonTip(1, "File Renamed", e.OldFullPath + " renamed to " + e.FullPath, ToolTipIcon.Info);                                
        }
    }

改变列表:

New Microsoft Excel ワークシート.xls  2011/10/10 11:00:15 Created C:'New Folder
B1F38000                2011/10/10 11:00:55 Created C:'New Folder
New Microsoft Excel ワークシート.xls~RF83f213.TMP 2011/10/10 11:01:16 Created C:'New Folder
New Microsoft Excel ワークシート.xls  2011/10/10 11:01:16 Deleted C:'New Folder   
New Microsoft Excel ワークシート.xls  2011/10/10 11:01:16 Renamed C:'New Folder
New Microsoft Excel ワークシート.xls~RF83f213.TMP 2011/10/10 11:01:18 Deleted C:'New Folder

如何在c#中观察excel文件的变化

您可以设置FileSystemWatcher只监视特定文件夹,因此您对filepath的检查是多余的。

否则,做你目前的事情,但检查触发事件的文件的文件名,看看它是否有XLS, XLSX, XLSM或文件上的任何其他Excel扩展名。