Pregunta

Quiero encontrar un texto, por ejemplo, "Joe" y quitarlo de donde se encuentra en la hoja de trabajo de Excel con C #?

¿Fue útil?

Solución

Usted tendría que utilizar el método Range.Replace, y simplemente reemplazar con una cadena vacía.

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

Otros consejos

Esto funciona para Excel 2016:

  • Buscar Microsoft.Office.Interop.Excel en su C :, copiarlo en su proyecto de C #, e incluir esto como una referencia.
  • versión Asamblea debe 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 bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top