Skip to content

Instantly share code, notes, and snippets.

@kujirahand
Created September 17, 2024 09:49
Show Gist options
  • Save kujirahand/d333bb6d5caec66c7753c52601476626 to your computer and use it in GitHub Desktop.
Save kujirahand/d333bb6d5caec66c7753c52601476626 to your computer and use it in GitHub Desktop.
カレントディレクトリにあるExcelファイルのセルを正規表現検索する
package main
import (
"fmt"
"os"
"regexp"
"strings"
"github.com/xuri/excelize/v2"
)
func main() {
// コマンドライン引数を取得 --- (*1)
args := os.Args
if len(args) < 2 {
fmt.Println("正規表現を指定してください")
return
}
// 正規表現をコンパイル --- (*2)
pattern := args[1]
re, err := regexp.Compile(pattern)
if err != nil {
fmt.Printf("正規表現のコンパイルに失敗: %v", err)
return
}
// カレントディレクトリのファイル一覧を取得 --- (*3)
files, err := os.ReadDir(".")
if err != nil {
fmt.Printf("ディレクトリの読み込みに失敗: %v", err)
}
// ファイル一覧を調査
for _, file := range files {
fname := file.Name()
if strings.HasSuffix(fname, ".xlsx") {
searchFile(file.Name(), re)
}
}
}
func searchFile(filename string, re *regexp.Regexp) {
// ファイルを検索 --- (*4)
fmt.Printf("%s:\n", filename)
// ファイルを開く
f, err := excelize.OpenFile(filename)
if err != nil {
fmt.Printf("ファイルの読み込みに失敗: %v", err)
return
}
// シート一覧を取得 --- (*5)
sheets := f.GetSheetList()
for _, sheet := range sheets {
// シートの行を全部取得 --- (*6)
rows, err := f.GetRows(sheet)
if err != nil {
continue
}
// 取得した行を調査 --- (*7)
for rowIndex, row := range rows {
matchCell := ""
disp := "|"
// セルを一つずつ調査 --- (*8)
for colIndex, cell := range row {
// cellの内容を正規表現で検索 --- (*9)
if !re.Match([]byte(cell)) {
disp += fmt.Sprintf("%s|", cell)
continue // 見つからなかった時
}
disp += fmt.Sprintf("[%s]|", cell)
cellName, _ := excelize.CoordinatesToCellName(colIndex+1, rowIndex+1)
matchCell = cellName
}
if matchCell != "" {
fmt.Printf("- %s.%s: %s\n", sheet, matchCell, disp)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment