Sometimes, you will need to open or write extremely large XLSX files, and the common routines in openpyxl won’t be able to handle that load. Fortunately, there are two modes that enable you to read and write unlimited amounts of data with (near) constant memory consumption.
Introducing
openpyxl.worksheet._read_only.ReadOnlyWorksheet
:
from openpyxl import load_workbook wb = load_workbook(filename='large_file.xlsx', read_only=True) ws = wb['big_data'] for row in ws.rows: for cell in row: print(cell.value) # Close the workbook after reading wb.close()
警告
openpyxl.worksheet._read_only.ReadOnlyWorksheet
is read-only
close()
方法。
Cells returned are not regular
openpyxl.cell.cell.Cell
but
openpyxl.cell._read_only.ReadOnlyCell
.
Read-only mode relies on applications and libraries that created the file providing correct information about the worksheets, specifically the used part of it, known as the dimensions. Some applications set this incorrectly. You can check the apparent dimensions of a worksheet using ws.calculate_dimension() . If this returns a range that you know is incorrect, say A1:A1 then simply resetting the max_row and max_column attributes should allow you to work with the file:
ws.reset_dimensions()
Here again, the regular
openpyxl.worksheet.worksheet.Worksheet
has been replaced by a faster alternative, the
openpyxl.worksheet._write_only.WriteOnlyWorksheet
. When you want to dump large amounts of data make sure you have
lxml
installed.
>>> from openpyxl import Workbook >>> wb = Workbook(write_only=True) >>> ws = wb.create_sheet() >>> >>> # now we'll fill it with 100 rows x 200 columns >>> >>> for irow in range(100): ... ws.append(['%d' % i for i in range(200)]) >>> # save the file >>> wb.save('new_big_file.xlsx') # doctest: +SKIP
If you want to have cells with styles or comments then use a
openpyxl.cell.WriteOnlyCell()
>>> from openpyxl import Workbook >>> wb = Workbook(write_only = True) >>> ws = wb.create_sheet() >>> from openpyxl.cell import WriteOnlyCell >>> from openpyxl.comments import Comment >>> from openpyxl.styles import Font >>> cell = WriteOnlyCell(ws, value="hello world") >>> cell.font = Font(name='Courier', size=36) >>> cell.comment = Comment(text="A comment", author="Author's Name") >>> ws.append([cell, 3.14, None]) >>> wb.save('write_only_file.xlsx')
This will create a write-only workbook with a single sheet, and append a row of 3 cells: one text cell with a custom font and a comment, a floating-point number, and an empty cell (which will be discarded anyway).
警告
create_sheet()
方法。
append()
. It is not possible to write (or read) cells at
arbitrary locations with
cell()
or
iter_rows()
.
openpyxl.utils.exceptions.WorkbookAlreadySaved
异常。