38
42

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->pandas->sqlite

Last updated at Posted at 2015-04-18

Excelのシートからsqlへ放り込むにはODBCのドライバを入れたり、vbaをコツコツと書かないといけないけどpythonだと簡単だよというお話。

sheet.PNG

↑C:\temp\Book1.xlsxにこんなシートが開いてるとして
pandas経由で放り込むとあら簡単。
めんどくさいcreateとかしなくてもto_sqlで一発でdbとtableの作成もやってくれる。

# -*- coding: utf-8 -*-
from xlwings import Workbook, Range
import pandas as pd
import pandas.io.sql as psql
import sqlite3

# 既に開いているExcelブックを読み込む
wb = Workbook(r'C:\temp\Book1.xlsx')
# A1から終端までのデータを取り込む
data = Range('A1').table.value
# pandasのデータフレームに変換する
df = pd.DataFrame(data[1:], columns=data[0])

with sqlite3.connect('fruit.db') as conn:
    psql.to_sql(df, 'fruit', conn)

cur = conn.execute('select * from fruit')
print(cur.fetchall())

今回はダイナミックに編集しているExcelを読み込むためにxlwingsを使ったけど保存済みのファイルならpd.read_excelで読み込んでもOK。

多分これが一番楽だと思います(フラグ)

38
42
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
38
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?