Question

Je veux trouver un texte par exemple « Joe » et le retirer de l'endroit où il est en feuille de calcul Excel avec C #?

Était-ce utile?

La solution

Vous devez utiliser la méthode Range.Replace et simplement remplacer par une chaîne vide.

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

Autres conseils

Cela fonctionne pour Excel 2016:

  • Rechercher Microsoft.Office.Interop.Excel sur votre C :, le copier dans votre projet C #, et inclure comme référence.
  • Version Assemblée devrait être 15.0.0.0.

Code:

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;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top