Domanda

voglio trovare un testo, ad esempio "Joe" e rimuoverlo dal dove è in foglio di lavoro Excel con C #?

È stato utile?

Soluzione

Si avrebbe bisogno di utilizzare il metodo Range.Replace, e semplicemente sostituirlo con una stringa vuota.

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

Altri suggerimenti

Questo funziona per Excel 2016:

  • Cerca Microsoft.Office.Interop.Excel sull'unità C :, copiarlo nel vostro progetto C #, e includere questo come riferimento.
  • Versione Assemblea deve essere 15.0.0.0.

Codice:

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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top