最近有需要用程式來產生excel報表的需求, 所以找了一個Open Libarary叫 openpyxl 還挺好用的

https://openpyxl.readthedocs.org/en/latest/index.html

這邊根據上面網址裡面記錄一些我自己常用的功能. 這樣就不用一直google了.

Install

pip install openpyxl

Create a workbook & sheet

from openpyxl import Workbook

wb = Workbook()
ws1 = wb.create_sheet() # insert at the end (default)
ws2 = wb.create_sheet(0) # insert at first position
ws1.title = "sheet 1" # set sheet name

Saving to a file

from openpyxl import Workbook

wb = Workbook()
wb.save('balances.xlsx'

Loading from a file

from openpyxl import load_workbook

wb2 = load_workbook('test.xlsx')
print wb2.get_sheet_names()

Write a workbook

from openpyxl import Workbook
from openpyxl.compat import range
from openpyxl.cell import get_column_letter

wb = Workbook()

dest_filename = 'empty_book.xlsx'

ws1 = wb.active
ws1.title = "range names"

for row in range(1, 40):
	ws1.append(range(600))

ws2 = wb.create_sheet(title="Pi")
ws2['F5'] = 3.14

wb.save(filename = dest_filename)