Question

I've to write a huge Excel file and the optimized writer in openpyxl is what I need.

The question is: is it possibile to set style and format of cells when using optimized writer? Style is not so important (I would only like to highlight column headers), but I need the correct number format for some columns containing currency values. I saw that ws.cell() method is not available when using optimized writer, so how to do it?

Thank you in advance for your help!

Was it helpful?

Solution 2

You could also look at the XlsxWriter module which allows writing huge files in optimised mode with formatting.

from xlsxwriter.workbook import Workbook

workbook = Workbook('file.xlsx', {'constant_memory': True})
worksheet = workbook.add_worksheet()
...

OTHER TIPS

As I can't comment, I'll post an update to Dean's answer here:

openpyxl's api (version 2.4.7) has changed slightly so that it should now read:

from openpyxl import Workbook
wb = Workbook( write_only = True )
ws = wb.create_sheet()

from openpyxl.writer.dump_worksheet import WriteOnlyCell
from openpyxl.styles import Font

cell = WriteOnlyCell(ws, value="highlight")
cell.font = Font(name='Courier', size=36)

cols=[]
cols.append(cell)
cols.append("some other value")
ws.append(cols)
wb.save("test.xlsx")

Hope it helps

Quote from docs:

Those worksheet only have an append() method, it’s not possible to access independent cells directly (through cell() or range()). They are write-only.

When you pass optimized_write=True to the Workbook constructor, openpyxl will use DumpWorksheet class instead of Worksheet. DumpWorksheet class is very limited in terms of styling and formatting.

But, look at append method - it matches the python type of data you pass to excel types. So, see correct cell formats in the result file after running this:

import datetime
from openpyxl import Workbook

wb = Workbook(optimized_write=True)
ws = wb.create_sheet()

for irow in xrange(5):
    ws.append([True, datetime.datetime.now(), 'test', 1, 1.25, '=D1+E1'])

wb.save('output.xlsx')

Speaking about changing the column headers style - just no way to do it using optimized writer.

Hope that helps.

You can use the WriteOnlyCell to do this.

from openpyxl import Workbook
wb = Workbook(optimized_write = True)
ws = wb.create_sheet()
from openpyxl.writer.dump_worksheet import WriteOnlyCell
from openpyxl.styles import Style, Font, PatternFill
cell = WriteOnlyCell(ws, value="highlight")
cell.style = Style(font=Font(name='Courier', size=36), fill=PatternFill(fill_type='solid',start_color='8557e5'))
cols=[]
cols.append(cell)
cols.append("some other value")
ws.append(cols)
wb.save("test.xlsx")

I hope this helps. You can use anything that the style will allow before appending it to the row for the worksheet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top