12
12

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.

MySQLのテーブルをExcelに取り込める形式で出力するBashスクリプト

Last updated at Posted at 2015-08-07

「MySQL の検索結果を Excel や Access に取り込みたい」というベタな要望を叶えるスクリプトです。
Excel 2013 で取り込めることを確認済みです。

やりたいこと

  1. 指定したテーブルを個別の CSV ファイルに出力する
  2. CSV の1行目はヘッダー行にする
  3. NULL は空文字にする (普通に出力すると \N という変な文字になるので)
  4. Excel で取り込めるよう Shift-JIS に変換する

スクリプト

config 内をお好みの値に修正してから実行してください。

下記の例を実行すると、/tmp/mysql_dump/ ディレクトリ内に clients.csv, points.csv, users.csv の3ファイルが作成されます。

# !/bin/sh
# ***************
# config
# ***************
id=DB_USER_NAME
pw=DB_USER_PASSWORD
db=DB_NAME
tables=("clients" "points" "users")
dir=/tmp/mysql_dump/

# ***************
# exec
# ***************
mkdir -p ${dir}
chmod 777 ${dir}

for table in ${tables[@]}; do
  f=${dir}${table}.csv
  header=${dir}header
  data=${dir}data

  echo "${table}..."
  rm -f ${f} ${header} ${data}

  mysql -u${id} -p${pw} ${db} -e "SELECT GROUP_CONCAT(COLUMN_NAME  SEPARATOR ',') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='${table}' INTO OUTFILE '${header}'"
  mysql -u${id} -p${pw} ${db} -e "SELECT * FROM ${table} INTO OUTFILE '${data}' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'"
  cat ${data} >> ${header}
  mv -f ${header} ${f}
  nkf -s --overwrite ${f}
  sed -i -e 's/\\N//g' ${f}
done

参考

12
12
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
12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?