简体   繁体   English

如何使用 openpyxl 在 XLSX 文件中逐个单元格地插入和格式化值

[英]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.

相关问题 无法使用Pandas或openpyxl在任何.xlsx文件的单元格中检测到EUR - Unable to detect EUR in a cell of any .xlsx file, using pandas or openpyxl openpyxl xlsx文件单元格值=无 - openpyxl xlsx file cell value = none OpenPyXl 如何将单元格格式化为日期 - OpenPyXl how to format cell as date 如何在openpyxl中访问单元格值 - How to access cell values in openpyxl 使用 Spreadsheett::ParseXLSX 从 .xlsx 文件复制单元格格式以使用 EXCEL:WRITER::XLSX 编写另一个单元格? - Copy the cell format from .xlsx file using Spreadsheett::ParseXLSX to write another cell using EXCEL:WRITER::XLSX? 如何在 excel 的一个单元格中插入 pandas 数据帧(使用 openpyxl),其中的值将用逗号分隔? - How to insert a pandas data frame in one cell in excel (using openpyxl), where the values will be separated with comma? 如何使用openpyxl / python读取Excel文件的合并单元格值? - How to read merged cell values of an excel file with openpyxl / python? 如何使用 OpenPyXL 设置货币的单元格格式? - How to set cell format of currency with OpenPyXL? 在 Excel 文件中,如何使用 openpyxl (Python) 查找单元格的背景颜色 - In a Excel file how to find the background color of a cell using openpyxl (Python) 如何使用openpyxl创建一个新的xlsx文件? - how to create a new xlsx file using openpyxl?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM