Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
openpyxlでExcelを操作
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import openpyxl
import os
def recreate_data(filename):
if os.path.exists(filename):
os.remove(filename)
wb = openpyxl.Workbook()
# rename first sheet 'Sheet' to 'Sheet1'
ws1 = wb.active
ws1.title = 'Sheet1'
ws1.append(['4/5/2015 1:34:02 PM', 'Apples', 73])
ws1.append(['4/5/2015 3:41:23 AM', 'Cherries', 85])
ws1.append(['4/6/2015 12:46:51 PM', 'Pears', 14])
ws1.append(['4/8/2015 8:59:43 AM', 'Oranges', 52])
ws1.append(['4/10/2015 2:07:00 AM', 'Apples', 152])
ws1.append(['4/10/2015 6:10:37 PM', 'Bananas', 23])
ws1.append(['4/10/2015 2:40:46 AM', 'Strawberries', 98])
wb.create_sheet('Sheet2')
wb.create_sheet('Sheet3')
wb.save(filename)
def main(filename):
wb = openpyxl.load_workbook(filename)
# シート名取得
for s in wb.get_sheet_names():
print('sheet name: ' + s)
# 現在のアクティブ
print(wb.active)
# シート名からシートを取得
sheet = wb.get_sheet_by_name('Sheet1')
print(sheet['A1'], sheet['A1'].value)
# セルへのアクセス
c = sheet['B1']
print(c.row, c.column, c.coordinate, c.value)
# Excelの行は1から数える。
for i in range(1, sheet.max_row+1):
print(i, sheet.cell(row=i, column=2).value, sheet[i])
if __name__ == '__main__':
exel_file = 'example.xlsx'
recreate_data(exel_file)
main(exel_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.