Hari ini saya ingin berkongsi dengan anda artikel tentang menggunakan openpyxl untuk mengendalikan Excel.
Perlu mengimport pelbagai data ke dalam Excel? Ingin menggabungkan berbilang Excel? Pada masa ini, terdapat banyak perpustakaan untuk Python memproses fail Excel, dan openpyxl adalah salah satu daripadanya dengan fungsi dan prestasi yang lebih baik. Seterusnya, saya akan memperkenalkan pelbagai operasi Excel kepada anda.
Buat fail Excel baharu
>>> from openpyxl import Workbook >>> wb = Workbook()
Buka fail Excel sedia ada
>>> from openpyxl import load_workbook >>> wb2 = load_workbook('test.xlsx')
Apabila membuka fail besar, gunakan mod baca sahaja atau tulis sahaja mengikut keperluan untuk mengurangkan penggunaan memori.
wb = load_workbook(filename='large_file.xlsx', read_only=True) wb = Workbook(write_only=True)
Dapatkan lembaran kerja aktif semasa:
>>> ws = wb.active
Buat lembaran kerja baharu:
>>> 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
Dapatkan lembaran kerja menggunakan nama lembaran kerja:
>>> ws3 = wb["New Title"]
Dapatkan semua nama lembaran kerja:
>>> print(wb.sheetnames) ['Sheet2', 'New Title', 'Sheet1'] 使用for循环遍历所有的工作表: >>> for sheet in wb: ... print(sheet.title)
4 Sel
>>> 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'
Gunakan format angka:
>>> 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)
>>> colC = ws['C'] >>> col_range = ws['C:D'] >>> row10 = ws[10] >>> row_range = ws[5:10]
>>> 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>
>>> 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>
>>> ws = wb.active >>> ws['C9'] = 'hello world' >>> tuple(ws.rows) ((, | , | ), ( | , | , | ), ( | , | , | ), ( | , | , | ), ( | , | , | ), ( | , | , | ), ( | , | , | ), ( | , | , | ), ( | , | , | )) |
>>> 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>))
>>> 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)))
>>> 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()用来批量删除行和列。
for row in ws.values: for value in row: print(value)
Atas ialah kandungan terperinci Automasi pejabat Python, kuasai operasi openpyxl dalam masa lima minit!. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!