Python辦公室自動化,五分鐘掌握openpyxl操作!

WBOY
發布: 2023-04-17 11:49:02
轉載
793 人瀏覽過

Python辦公室自動化,五分鐘掌握openpyxl操作!

今天要來跟大家分享一篇用openpyxl操作Excel的文章。

各種資料需要導入Excel?多個Excel要合併?目前,Python處理Excel檔案有很多函式庫,openpyxl算是其中功能和效能做的比較好的一個。接下來我將為大家介紹各種Excel操作。

1、開啟Excel檔案

新一個Excel檔案

>>> from openpyxl import Workbook
>>> wb = Workbook()
登入後複製

開啟現有Excel檔案

>>> from openpyxl import load_workbook
>>> wb2 = load_workbook('test.xlsx')
登入後複製

開啟大檔案時,根據需求使用唯讀或只寫模式減少記憶體消耗。

wb = load_workbook(filename='large_file.xlsx', read_only=True)
wb = Workbook(write_only=True)
登入後複製

2、取得、建立工作表

取得目前活動工作表:

>>> ws = wb.active
登入後複製

建立新的工作表:

>>> ws1 = wb.create_sheet("Mysheet") # insert at the end (default)
 # or
 >>> ws2 = wb.create_sheet("Mysheet", 0) # insert at first position
 # or
 >>> ws3 = wb.create_sheet("Mysheet", -1) # insert at the penultimate position
登入後複製

使用工作表名字來取得工作表:

>>> ws3 = wb["New Title"]
登入後複製

取得所有的工作表名稱:

>>> print(wb.sheetnames)
 ['Sheet2', 'New Title', 'Sheet1']
使用for循环遍历所有的工作表:
 >>> for sheet in wb:
 ... print(sheet.title)
登入後複製

3、儲存

##在網路中儲存到流中使用:

>>> from tempfile import NamedTemporaryFile
 >>> from openpyxl import Workbook
 >>> wb = Workbook()
 >>> with NamedTemporaryFile() as tmp:
 wb.save(tmp.name)
 tmp.seek(0)
 stream = tmp.read()
保存到文件:
 >>> wb = Workbook()
 >>> wb.save('balances.xlsx')
保存为模板:
 >>> wb = load_workbook('document.xlsx')
 >>> wb.template = True
 >>> wb.save('document_template.xltx')
登入後複製

4、單元格


單元格位置作為工作表的鍵直接讀取:

>>> c = ws['A4']
登入後複製

為單元格賦值:

>>> ws['A4'] = 4
 >>> c.value = 'hello, world'
登入後複製

多個單元格可以使用切片存取單元格區域:


>>> cell_range = ws['A1':'C2']
登入後複製

使用數值格式:

>>> # set date using a Python datetime
 >>> ws['A1'] = datetime.datetime(2010, 7, 21)
 >>>
>>> ws['A1'].number_format
 'yyyy-mm-dd h:mm:ss'
登入後複製

使用公式:

>>> # add a simple formula
 >>> ws["A1"] = "=SUM(1, 1)"
登入後複製

合併單元格時,除左上角單元格外,所有單元格都將從工作表中刪除:

>>> 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)
登入後複製

5、行、列


可以單獨指定行、列、或行列的範圍:

>>> colC = ws['C']
 >>> col_range = ws['C:D']
 >>> row10 = ws[10]
 >>> row_range = ws[5:10]
登入後複製

可以使用Worksheet.iter_rows()方法遍歷行:

>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2):
 ...for cell in row:
 ...print(cell)
 <Cell Sheet1.A1>
 <Cell Sheet1.B1>
 <Cell Sheet1.C1>
 <Cell Sheet1.A2>
 <Cell Sheet1.B2>
 <Cell Sheet1.C2>
登入後複製

同樣的Worksheet.iter_cols()方法將遍歷列:

>>> for col in ws.iter_cols(min_row=1, max_col=3, max_row=2):
 ... for cell in col:
 ... print(cell)
 <Cell Sheet1.A1>
 <Cell Sheet1.A2>
 <Cell Sheet1.B1>
 <Cell Sheet1.B2>
 <Cell Sheet1.C1>
 <Cell Sheet1.C2>
登入後複製

或列,可以使用Worksheet.rows屬性:

>>> ws = wb.active
 >>> ws['C9'] = 'hello world'
 >>> tuple(ws.rows)
 ((, , ),
 (, , ),
 (, , ),
 (, , ),
 (, , ),
 (, , ),
 (, , ),
 (, , ),
 (, , ))
登入後複製

或Worksheet.columns屬性:

>>> tuple(ws.columns)
 ((<Cell Sheet.A1>,
 <Cell Sheet.A2>,
 <Cell Sheet.A3>,
 <Cell Sheet.A4>,
 <Cell Sheet.A5>,
 <Cell Sheet.A6>,
 ...
 <Cell Sheet.B7>,
 <Cell Sheet.B8>,
 <Cell Sheet.B9>),
 (<Cell Sheet.C1>,
 <Cell Sheet.C2>,
 <Cell Sheet.C3>,
 <Cell Sheet.C4>,
 <Cell Sheet.C5>,
 <Cell Sheet.C6>,
 <Cell Sheet.C7>,
 <Cell Sheet.C8>,
 <Cell Sheet.C9>))
登入後複製

使用Worksheet.append()或迭代使用Worksheet.cell()新增一行資料:

>>> for row in range(1, 40):
 ... ws1.append(range(600))
 >>> 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)))
登入後複製

插入操作比較麻煩。可以使用Worksheet.insert_rows()插入一行或幾行:

>>> from openpyxl.utils import get_column_letter
 >>> ws.insert_rows(7)
>>> row7 = ws[7]
>>> for col in range(27, 54):
 ... _ = ws3.cell(column=col, row=7, value="{0}".format(get_column_letter(col)))
Worksheet.insert_cols()操作类似。Worksheet.delete_rows()和Worksheet.delete_cols()用来批量删除行和列。
登入後複製

6、只讀取值


使用Worksheet.values屬性遍歷工作表中的所有行,但只傳回儲存格值:

for row in ws.values:
for value in row:
print(value)
登入後複製

Worksheet.iter_rows()和Worksheet.iter_cols()可以設定values_only參數來只傳回儲存格的值:


>>> for row in ws.iter_rows(min_row=1, max_col=3, max_row=2, values_only=True):
 ... print(row)
 (None, None, None)
(None, None, None)
登入後複製

以上是Python辦公室自動化,五分鐘掌握openpyxl操作!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:51cto.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!