LoginSignup
5

More than 3 years have passed since last update.

PythonでExcel基本操作

Posted at

はじめに

プロジェクト開発ではExcelの操作はよくあると思います。
簡単に操作方法をまとめてみます。

ライブラリインストール

pip install xlsxwriter

※pipバージョン古い場合はupgradeしたほうがよい
python -m pip install --upgrade pip

データをExcelに書き込みサンプル

excel.py
import xlsxwriter

data = (
    ["田中 一郎", 20],
    ["山田 一郎", 23],
    ["鈴木 一郎", 21]
)

workBook = xlsxwriter.Workbook("user.xlsx")

workSheet = workBook.add_worksheet(name="ユーザー一覧")

row, col = 0, 0

# dataをExcelに書き込み
for userName, age in data:
    workSheet.write(row, col, userName)
    workSheet.write(row, col + 1, age)

    # 次の行へ
    row += 1

# 平均年齢
workSheet.write(row, 0, "平均年齢")
workSheet.write(row, 1, "=AVERAGE(B1, B3)")
workBook.close()

結果:
image.png

簡単ですね。

各フォーマットのメソッド

  • 文字列: wirte_string()
  • 数字: write_number()
  • 空白: write_blank()
  • 計算式: write_formula()
  • 日付: write_datetime()
  • true/false: write_boolean()
  • URL: write_url()

詳細はhttps://xlsxwriter.readthedocs.io/working_with_data.html

簡単なチャート例

chart.py
import xlsxwriter

workBook = xlsxwriter.Workbook('chart.xlsx')

worksheet = workBook.add_worksheet()
bold = workBook.add_format({'bold': 1})

headings = ['言語', '人気度']
data = [
    ['Rust', 'Go', 'Kotlin', 'Node.js'],
    [40, 20, 10, 30],
]

# excelにデータをインサート(ダミーの数字です)
worksheet.write_row('A1', headings, bold)
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])

# チャート種類を指定
pieChart = workBook.add_chart({'type': 'pie'})

# 範囲指定
pieChart.add_series({
    'name':       '言語の人気度',
    'categories': ['Sheet1', 1, 0, 4, 0],
    'values':     ['Sheet1', 1, 1, 4, 1],
})

# タイトル
pieChart.set_title({'name': '言語の人気度'})

pieChart.set_style(10)

# チャートをインサート
worksheet.insert_chart('C2', pieChart, {'x_offset': 25, 'y_offset': 10})

workBook.close()

結果:
image.png

いろいろな種類のチャートがあります。
https://xlsxwriter.readthedocs.io/chart_examples.html

xlsxwriter:https://xlsxwriter.readthedocs.io/

以上

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
5