python+excel=openpyxl(二)

新夢想IT發表於2022-12-21



建立一個workbook

>>> from openpyxl import Workbook

>>> from openpyxl.utils 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

>>>

>>> ws3 = wb.create_sheet(title="Data")

>>> for row in range(10, 20):

...     for col in range(27, 54):

...         _ = ws3.cell(column=col, row=row, value="{0}".format(get_column_letter(col)))

>>> print(ws3['AA10'].value)

AA

>>> wb.save(filename = dest_filename)



讀取一張已存在的workbook


直接透過sheet的title獲取整張表,然後透過具體cell的名稱來獲取值

>>> from openpyxl import load_workbook


>>> wb = load_workbook(filename = 'empty_book.xlsx')

>>> sheet_ranges = wb['range names']

>>> print(sheet_ranges['D18'].value)

3



使用number_format獲取單元格格式


>>> import datetime

>>> from openpyxl import Workbook

>>> wb = Workbook()

>>> ws = wb.active

>>> # set date using a Python datetime

>>> ws['A1'] = datetime.datetime(2010, 7, 21)

>>>

>>> ws['A1'].number_format

'yyyy-mm-dd h:mm:ss'


使用公式

>>> import openpyxl

>>> wb = openpyxl.load_workbook('F:\\PycharmProjects\\untitled\\測試表格.xlsx')

>>> ws = wb.active

>>> ws['A11'] = '=SUM(A1:B1)'

>>> wb.save(‘F:\\PycharmProjects\\untitled\\測試表格.xlsx’)


結果如下圖

新夢想技術分享


openpyxl模組不會評估公式,但是它可以判斷公式的名稱是否有效:

>>> from openpyxl.utils import FORMULAE

>>> "HEX2DEC" in FORMULAE

True


如果你嘗試去使用一個未知的公式,所謂未知公式就是指這個公式沒有包含在openpyxl初始化的模組中。這一類公式就必須使用 _xlfn. 作為字首來參與運算


合併/取消合併 單元格

合併單元格時,除左上角以外的所有單元格都將從工作表中刪除。 為了攜帶合併單元格的邊界資訊,將合併單元格的邊界單元格建立為MergeCells,它們始終具有值None。 有關格式化合並單元格的資訊,請參見樣式化合並單元格。

>>> from openpyxl.workbook import Workbook

>>>

>>> wb = Workbook()

>>> ws = wb.active

>>>

>>> ws.merge_cells('A2:D2')

>>> ws.unmerge_cells('A2:D2')

>>>

>>> # or equivalently

>>> ws.merge_cells(start_row=2, start_column=1, end_row=4, end_column=4)

>>> ws.unmerge_cells(start_row=2, start_column=1, end_row=4, end_column=4)



插入圖片


>>> from openpyxl import Workbook

>>> from openpyxl.drawing.image import Image

>>>

>>> wb = Workbook()

>>> ws = wb.active

>>> ws['A1'] = 'You should see three logos below'

>>> # create an image

>>> img = Image('logo.png')

>>> # add to worksheet and anchor next to cells

>>> ws.add_image(img, 'A1')

>>> wb.save('logo.xlsx') 



隱藏單元格


>>> import openpyxl

>>> wb = openpyxl.Workbook()

>>> ws = wb.create_sheet()

>>> ws.column_dimensions.group('A','D', hidden=True)

>>> ws.row_dimensions.group(1,10, hidden=True)

>>> wb.save('group.xlsx')


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69940641/viewspace-2928831/,如需轉載,請註明出處,否則將追究法律責任。

相關文章