サーバレス練習帳

着眼大局着手小局

【python】ExcelのデータをSQLITEに!

やればできるじゃないか!

# EXCEL形式の設定情報をSQLITE形式に変換します。
# ちなみにエクセル内では縦軸がrow、横軸がcolです。
##### IMPORT
import xlrd
import sqlite3
from contextlib import closing

##### CONST
book = xlrd.open_workbook('./conf.xlsx')
db = './conf.sdb'

##### IMPLEMENTATION
with closing(sqlite3.connect(db)) as conn:
    c = conn.cursor()

    ### テーブル作成
    # PageConf
    create_table = '''create table PageConf (
                        page_id INTEGER,
                        name TEXT,
                        url TEXT)'''

    c.execute(create_table)


    ### Excelデータ読み出し
    # PageConf 
    sheet = book.sheet_by_name('PageConf')

    for row_index in range(sheet.nrows):
        if row_index >= 4 :
            page_id = int (sheet.cell_value(rowx=row_index, colx=0))
            name = sheet.cell_value(rowx=row_index, colx=1)
            url = sheet.cell_value(rowx=row_index, colx=2)
            sql = 'insert into PageConf (page_id, name, url) values (?,?,?)'
            data = (page_id, name, url)
            c.execute(sql, data)


    ### データ確認
    # PageConf
    print('PageConf')
    select_sql = 'select * from PageConf'
    for row in c.execute(select_sql):
        print(row)