如何使用 C# Interop 保留最新记录并删除旧记录
我有一个包含四列的 xls 文件,
ID Name Date File
1 charlie 01/09/2011 1.txt
2 charlie 12/25/2005 2.txt
3 nero 11/11/2011 3.txt
4 charlie 12/09/2011 4.txt
该过程将能够删除 charlie 的旧记录并保留最新的记录 基于名称和日期的其他列将被忽略。
在此示例中,预期 xls 将包含以下记录:
ID Name Date File
3 nero 11/11/2011 3.txt
4 charlie 12/09/2011 4.txt
以 MM/DD/YYYY 表示的日期。
任何建议将不胜感激
I have an xls file with four columns
ID Name Date File
1 charlie 01/09/2011 1.txt
2 charlie 12/25/2005 2.txt
3 nero 11/11/2011 3.txt
4 charlie 12/09/2011 4.txt
the process will be able to delete the older records of charlie and keep latest one
based on Name and Date other to columns are ignored.
expected xls will have following records
ID Name Date File
3 nero 11/11/2011 3.txt
4 charlie 12/09/2011 4.txt
in this example the date in MM/DD/YYYY.
Any suggestions will be appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信您需要按名称分组,并获取每个分组的最近日期,然后从结果中仅选择
ID
。从 Table1 GROUP BY Table1.Name 中选择 Table1.ID、MAX(Table1.Date)
。因此,在获得此查询后,只需使用ID
字段即可。接下来执行删除查询(伪代码)
DELETE FROM [Table] WHERE [Table].ID NOT IN(上面的结果)
以下是使用 LINQ to SQL 完成的:
此代码是针对数据库完成的,但基本逻辑仍然适用于 Excel 文件。
I believe you would need to group by the name, and take the recent date for each grouping, then select only the
ID
from the result.SELECT Table1.ID, MAX(Table1.Date) FROM Table1 GROUP BY Table1.Name
. So after you get this query then just use theID
field.Next do a delete query (Psuedo Code)
DELETE FROM [Table] WHERE [Table].ID NOT IN (result from above)
The following is done with LINQ to SQL:
This code is done against a database, but the basic logic still applies to an excel file.
如果您不确定是否希望将其作为使用 C# 和 COM Interop to Excel 的外部程序,您可能会在此处找到一些有关宏的有用信息:
http://office.microsoft.com/en-gb/excel-help/create-or-delete-a-macro-HP010014111.aspx
否则,您需要创建一个新的Visual Studio 中的 C# 项目并添加对 Microsoft.Office.Core 和 Microsoft.Office.Interop.Excel 的引用。
完成后,您可以执行以下操作(注意:您需要更好的错误清理):
If you're not sure you want this as an external program using c# with COM Interop to Excel, you might find some useful info on macros here:
http://office.microsoft.com/en-gb/excel-help/create-or-delete-a-macro-HP010014111.aspx
Otherwise you'll need to create a new C# project in visual studio and add references to Microsoft.Office.Core and Microsoft.Office.Interop.Excel.
Once that's done, you could do something like the following (Note: you'll want better error cleanup):