5 分鐘掌握 openpyxl 操作:Python 輕松處理 Excel

來(lái)源:python中文社區(qū)
各種數(shù)據(jù)需要導(dǎo)入Excel?多個(gè)Excel要合并?目前,Python處理Excel文件有很多庫(kù),openpyxl算是其中功能和性能做的比較好的一個(gè)。接下來(lái)我將為大家介紹各種Excel操作。
打開(kāi)Excel文件
新建一個(gè)Excel文件
>>> from openpyxl import Workbook
>>> wb = Workbook()
打開(kāi)現(xiàn)有Excel文件
>>> from openpyxl import load_workbook
>>> wb2 = load_workbook('test.xlsx')
打開(kāi)大文件時(shí),根據(jù)需求使用只讀或只寫(xiě)模式減少內(nèi)存消耗。
wb = load_workbook(filename='large_file.xlsx', read_only=True)
wb = Workbook(write_only=True)
獲取、創(chuàng)建工作表
獲取當(dāng)前活動(dòng)工作表:
>>> ws = wb.active
創(chuàng)建新的工作表:
>>> 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循環(huán)遍歷所有的工作表:
>>> for sheet in wb:
... print(sheet.title)
保存
保存到流中在網(wǎng)絡(luò)中使用:
>>> 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')
單元格
單元格位置作為工作表的鍵直接讀取:
>>> c = ws['A4']
為單元格賦值:
>>> ws['A4'] = 4
>>> c.value = 'hello, world'
多個(gè)單元格可以使用切片訪問(wèn)單元格區(qū)域:
>>> cell_range = ws['A1':'C2']
使用數(shù)值格式:
>>> # 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)"
合并單元格時(shí),除左上角單元格外,所有單元格都將從工作表中刪除:
>>> 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)
行、列
可以單獨(dú)指定行、列、或者行列的范圍:
>>> 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)
((<Cell Sheet.A1>, <Cell Sheet.B1>, <Cell Sheet.C1>),
(<Cell Sheet.A2>, <Cell Sheet.B2>, <Cell Sheet.C2>),
(<Cell Sheet.A3>, <Cell Sheet.B3>, <Cell Sheet.C3>),
(<Cell Sheet.A4>, <Cell Sheet.B4>, <Cell Sheet.C4>),
(<Cell Sheet.A5>, <Cell Sheet.B5>, <Cell Sheet.C5>),
(<Cell Sheet.A6>, <Cell Sheet.B6>, <Cell Sheet.C6>),
(<Cell Sheet.A7>, <Cell Sheet.B7>, <Cell Sheet.C7>),
(<Cell Sheet.A8>, <Cell Sheet.B8>, <Cell Sheet.C8>),
(<Cell Sheet.A9>, <Cell Sheet.B9>, <Cell Sheet.C9>))
或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()新增一行數(shù)據(jù):
>>> 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()操作類(lèi)似。Worksheet.delete_rows()和Worksheet.delete_cols()用來(lái)批量刪除行和列。
只讀取值
使用Worksheet.values屬性遍歷工作表中的所有行,但只返回單元格值:
for row in ws.values:
for value in row:
print(value)
Worksheet.iter_rows()和Worksheet.iter_cols()可以設(shè)置values_only參數(shù)來(lái)僅返回單元格的值:
>>> 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)作者:Sinchard,主攻Python庫(kù)文檔翻譯,開(kāi)發(fā)代碼片段,源碼分析
Blog:zhihu.com/people/aiApple
- EOF -
推薦閱讀:
