0
1

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.

golangでExcelの列番号を英文字にする

0
Last updated at Posted at 2018-02-05

モチベ

excelize の引数が列番号じゃなく英文字でしか渡せないのでコンバーターがほしかった。

まぁ、この辺りに答えはあったんですけど、自分でも作りたかった。

というか PR送ったら取り込んでくれたりしないだろうか...

参考資料

Excel で列番号を英文字に変換する方法
https://support.microsoft.com/ja-jp/help/833402/how-to-convert-excel-column-numbers-into-alphabetical-characters

コード

package main

import (
	"fmt"
	"strconv"
)

func conv(i int) string {
	if i <= 0 {
		return ""
	}

	j := (i - 1) % 26
	l := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	s := conv((i - j) / 26)
	return s + string(l[j])
}

func GetAxis(row, col int) (string, error) {
	if col <= 0 {
		return "", fmt.Errorf("column value was invalid")
	}

	if row <= 0 {
		return "", fmt.Errorf("row value was invalid")
	}

	cstr := conv(col)
	rstr := strconv.Itoa(row)
	return cstr + rstr, nil
}

func main() {
	if axis, err := GetAxis(1, 1); err != nil {
		panic(err)
	} else {
		fmt.Println(axis) // A1
	}

	if axis, err := GetAxis(12, 26); err != nil {
		panic(err)
	} else {
		fmt.Println(axis) // Z12
	}

	if axis, err := GetAxis(123, 30); err != nil {
		panic(err)
	} else {
		fmt.Println(axis) // AD123
	}

	if axis, err := GetAxis(1234, 52); err != nil {
		panic(err)
	} else {
		fmt.Println(axis) // AZ1234
	}

	if axis, err := GetAxis(12345, 53); err != nil {
		panic(err)
	} else {
		fmt.Println(axis) // BA12345
	}

	if axis, err := GetAxis(123456, 864); err != nil {
		panic(err)
	} else {
		fmt.Println(axis) // AGF123456
	}

	if axis, err := GetAxis(12, 0); err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(axis)
	}

	if axis, err := GetAxis(0, 1); err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(axis)
	}
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?