您可以使用 COM 互操作来完成所有这些工作。确保您的项目引用了 Excel 互操作。(我相信你需要在你的机器上安装 excel)
using System.IO;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
然后应用
class Program
{
static void Main(string[] args)
{
var mypath = @"c:\my\search\directory";
string[] files = Directory.GetFiles(mypath, "*abc.xls", SearchOption.AllDirectories);
foreach (var file in files)
{
Find(Path.Combine(mypath,file));
}
}
private static void Find(string path)
{
object missing = null;
Excel.Range currentFind = null;
Excel.Range firstFind = null;
var app = new Excel.Application();
app.Visible = true;
Excel.Workbook workbook = app.Workbooks.Open(path, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
var worksheet = workbook.Sheets[1];
Excel.Range foundNames = worksheet.Range["A1", "B3"];
// You should specify all these parameters every time you call this method,
// since they can be overridden in the user interface.
currentFind = foundNames.Find("Peter, Paul, Mary", LookIn: XlFindLookIn.xlValues, LookAt: XlLookAt.xlPart);
currentFind.Replace(What:"Peter, Paul, Mary", Replacement:"Peter, John, Susan");
workbook.Save();
}
}
此示例假定所有内容都在 A1 和 B3 中的第一个工作表上。显然,您的工作表会有所不同,因此需要更改这些值以反映这一点。此外,您可以删除“visible=true”,可能会加快速度。我这样做只是为了让我可以看到我的应用程序在做什么。