Pergunta

Eu quero encontrar algum texto, por exemplo, "Joe" e removê-lo onde ele está na planilha do Excel com C #?

Foi útil?

Solução

Você precisa usar o método Range.Replace, e simplesmente substituir por uma cadeia vazia.

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

Outras dicas

Isso funciona para Excel 2016:

  • Pesquise Microsoft.Office.Interop.Excel em seu C :, copiá-lo em seu projeto C #, e incluir isso como uma referência.
  • Versão Assembléia deve ser 15.0.0.0.

Código:

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;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top