3

我想找到一些文本,例如“Joe”并将其从 Excel 工作表中使用 C# 的位置删除?

4

2 回答 2

7

您将需要使用 Range.Replace 方法,并简单地替换为空字符串。

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;
}
于 2009-02-07T13:54:57.690 回答
0

这适用于Excel 2016

  • 在您的 C: 上搜索Microsoft.Office.Interop.Excel,将其复制到您的 C# 项目中,并将其作为参考。
  • 汇编版本应该是15.0.0.0.

代码:

Excel.DisplayAlerts = false; // Prevent "Nothing found" dialogs.

var Excel = (Microsoft.Office.Interop.Excel.Application)ExcelDnaUtil.Application;

foreach(Worksheet sheet in Excel.Sheets)
{
    bool success = sheet.Rows.Replace(What: "ABC",Replacement: "DEF");
}

Excel.DisplayAlerts = true;
于 2017-05-25T11:54:04.893 回答