2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Excelの全角数値を半角数値に変換する

Posted at

経緯

前職SIerの自称・技術力高い上司(50代)が、顧客から「全角数値を半角数値に変換できないか?」という要望に対して、「技術的に難しい」と回答したらしい。

自称・技術力高い上司が***「全角から半角に変換できない」***というからには、おそらく難しいのだろうと思ったのであるが、(不慣れな)Go言語を用いて対応可能かを検証してみた。

やること

同じフォルダにエクセル(.xlsxのみ)を保存して実行すると、copy_***.xlsxというファイルが作成され、全角数値だった箇所のみが半角数値に変換される

ソース

main.go
package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"regexp"
	"strings"
	"time"

	"github.com/tealeg/xlsx"
)

func main() {
	dt1 := time.Now()

	var files []string
	files = GetFiles() // カレントディレクトリのエクセルを取得
	for _, file := range files {
		fmt.Println("ファイル名", file)

		copyfile := "copy_" + file
		err := os.Link(file, copyfile) // ファイルのコピー
		if err != nil {
			fmt.Printf(err.Error())
		}
		excel, err1 := xlsx.OpenFile(copyfile) // コピーしたファイルを開く

		if err1 != nil {
			fmt.Printf(err1.Error())
		}

		for _, sheet := range excel.Sheets {
			fmt.Println("シート名", sheet.Name)
			for _, row := range sheet.Rows {
				for _, cell := range row.Cells {
					v := cell.String()
					val := ZenkakuToHnakaku(v)
					// 変換不要なセルもあるが、とりあえず全て書き換え
					// fmt.Println(val)
					cell.Value = val
					//cell.Value = fmt.Sprintf(val)
				}
			}
		}

		// ファイルを保存
		err = excel.Save(copyfile)
		if err != nil {
			fmt.Printf(err.Error())
		}

	}

	dt2 := time.Now()
	fmt.Println(dt2.Sub(dt1)) //Excelファイル変換時間

}

func GetFiles() []string {
	dir, _ := os.Getwd() //カレントディレクトリ
	//dir := "/home/.../" //フォルダを直接指定する場合
	files, err := ioutil.ReadDir(dir)
	if err != nil {
		panic(err)
	}

	var paths []string
	for _, file := range files {
		if !file.IsDir() && path.Ext(file.Name()) == ".xlsx" &&
			!regexp.MustCompile(`^~$*`).Match([]byte(file.Name())) {
			paths = append(paths, file.Name())
		}
	}
	return paths
}

func ZenkakuToHnakaku(str string) string {
	// Replacerを使って置換する
	r := strings.NewReplacer("0", "0", "1", "1", "2", "2", "3", "3", "4", "4", "5", "5", "6", "6", "7", "7", "8", "8", "9", "9")
	resStr := r.Replace(str)
	return resStr
}

結論

簡単にできた。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?