2
我有一些代码来替换Excel项目中的文本(下面发布),这段代码就像一个魅力。但我也想要替换文本实例的数量。 有什么办法可以得到它吗?C#Excel互操作计数和替换
static void ReplaceTextInExcelFile(string filename, string replace, string replacement)
{
object m = Type.Missing;
// open excel.
Application app = new ApplicationClass();
// open the workbook.
Workbook wb = app.Workbooks.Open(
filename,
m, false, m, m, m, m, m, m, m, m, m, m, m, m);
// get the active worksheet. (Replace this if you need to.)
Worksheet ws = (Worksheet)wb.ActiveSheet;
// get the used range.
Range r = (Range)ws.UsedRange;
// call the replace method to replace instances.
bool success = (bool)r.Replace(
replace,
replacement,
XlLookAt.xlWhole,
XlSearchOrder.xlByRows,
true, m, m, m);
// save and close.
wb.Save();
app.Quit();
app = null;
}
试过这种code..it总是返回数2. start.replace函数替换所有情况下,如果在一气呵成的文字。 – Sunny
Otherway is to'start.value = replacement;'并删除'start.Replace' – perilbrain
感谢您的帮助。我通过循环遍历excel中的每个单元并执行匹配来完成它。使用正则表达式来让我匹配。我有一个单词列表来比较每个单元格。这种方法使我能够替换并获得计数。 – Sunny