使用C#在Excel中查找和替换文本 [英] Find and replace text in Excel using C#

查看:644
本文介绍了使用C#在Excel中查找和替换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用C#在Excel中查找和替换一组文本,此外,我希望此替换仅发生在第一行中.

I would like to find and replace a group of text in Excel using C#, moreover I want this replace to happen to text in the first row only.

我已经使用Google并找到了一些付费资源,例如Aspose API,Spire.Xls等,但是我正在寻找一种开源资源或任何其他有效的方法来实现这一目标.请提出建议.

I have used Google and found a few paid resource like Aspose API,Spire.Xls,etc, but I am looking for an open source resource or any other efficient way to achieve this. Please suggest.

推荐答案

尝试一下:

Public 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;
}

这篇关于使用C#在Excel中查找和替换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆