2012-08-22 43 views
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; 
} 

回答

1

你不能直接这样做,但你可以运行FindFindNext功能,然后替换无论是在search.This发现将打开一个范围内采取更换的次数。

Range r = (Range)ws.UsedRange; 
int count=0; 

Range first=r.Find(replace,m,m,XlLookAt.xlWhole,XlSearchOrder.xlByRows,m,m,m,m); 
if(first!=null) 
{count++; 
Range start=first; 
do 
{ 
    start.Value=replacement; 
    count++; 
    start=r.FindNext(m); 
} 
while(start!=first); 

//do whatever with count 
+0

试过这种code..it总是返回数2. start.replace函数替换所有情况下,如果在一气呵成的文字。 – Sunny

+0

Otherway is to'start.value = replacement;'并删除'start.Replace' – perilbrain

+0

感谢您的帮助。我通过循环遍历excel中的每个单元并执行匹配来完成它。使用正则表达式来让我匹配。我有一个单词列表来比较每个单元格。这种方法使我能够替换并获得计数。 – Sunny