LoginSignup
1
3

More than 5 years have passed since last update.

Excelファイルくし刺し検索置換

Last updated at Posted at 2017-10-19

複数のExcelファイルをくし刺し検索置換

Excelファイルを扱う話題最終編。

ClosedXMLを使って、C#でExcelファイルのセル中の文字を検索/置換する。
テキストボックスをふたつつくって、ボタンのイベントで呼ぶだけ。
foreachでbook, sheet, row, cellを回して、文字(value)を置換するだけでできる。

    string[] files = Directory.GetFiles(KeywordTextBox.Text, "*.xlsx");
    foreach (string file in files)
    {
        string savename = Path.GetDirectoryName(file) + @"\" + Path.GetFileNameWithoutExtension(file) + "2.xlsx";
        using (var wb = new XLWorkbook(file))
        {
            foreach (var worksheet in wb.Worksheets)
            {
                foreach (var line in worksheet.Rows)
                {
                    for (int i = 0; i < 65500; i++)
                    {
                        IXLCell cell = worksheet.Cell(line.Number, i);
                        cell.Value = cell.Value.ToString().Replace(ExcelKeywordTextBox.Text, ExcelChange2KeywordTextBox.Text);
                    }
                }
            }
            wb.SaveAs(savename);
        }
    }
}

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3