[英]How to insert and format values cell by cell in an XLSX file using openpyxl
I am trying to write an XLSX file using the openpyxl module.我正在尝试使用 openpyxl 模块编写一个 XLSX 文件。 I am using the
append()
method to insert the values row by row.我正在使用
append()
方法逐行插入值。 But I want to insert the values cell by cell instead.但我想逐个单元格地插入值。 I would also like to format the cell (font, colour, alignment etc).
我还想格式化单元格(字体、颜色、alignment 等)。 Please help me.
请帮我。
You can set all that cell by cell (if that is what you need) using openpyxl.您可以使用 openpyxl 逐个设置所有单元格(如果这是您需要的话)。 Here is a small example which sets the value, name (named_range) and some style of cells in a workbook:
这是一个小示例,它设置工作簿中的值、名称(named_range)和某些样式的单元格:
from openpyxl.workbook import Workbook
wb = Workbook()
dest_filename = r'empty_book.xlsx'
ws = wb.worksheets[0]
name = 'name'
for col_idx in xrange(1, 101):
col = get_column_letter(col_idx)
for row in xrange(1, 1001):
ws.cell('%s%s'%(col, row)).value = '%s%s' % (col, row)
ws.cell('%s%s'%(col, row)).style.fill.fill_type = 'solid'
ws.cell('%s%s'%(col, row)).style.fill.start_color.index = openpyxl.style.Color.DARKYELLOW
wb.create_named_range(name+str(i), ws, '%s%s'%(col, row))
wb.save(filename = dest_filename)
Look up the Style class in the openpyxl documentation to learn more about how to set individual formattings.在 openpyxl 文档中查找样式 class 以了解有关如何设置单个格式的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.