C# を使用して Excel ワークシート内のテキストを検索して削除する

StackOverflow https://stackoverflow.com/questions/523690

  •  22-08-2019
  •  | 
  •  

質問

C# を使用して、「Joe」などのテキストを検索し、Excel ワークシート内の場所から削除したいのですが?

役に立ちましたか?

解決

あなたは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;
}

他のヒント

これは、 Excel 2016:

  • 検索する Microsoft.Office.Interop.Excel C: 上で、それを 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;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top