openpyxl:无需迭代即可将值或格式应用于 Excel 单元格范围
openpyxl: assign value or apply format to a range of Excel cells without iteration
我想应用特定格式或为 Excel 单元格范围分配值,而不遍历每个单元格。我目前正在使用这个脚本:
from openpyxl import Workbook
from openpyxl.styles import Font
wb = Workbook()
ws = wb.active
## With iterations
# Apply style
for i, rowOfCellObjects in enumerate(ws['A1':'C4']):
for n, cellObj in enumerate(rowOfCellObjects):
cellObj.fill = Font(name='Times New Roman')
# Assign singular value to all cells
for i, rowOfCellObjects in enumerate(ws['A1':'C4']):
for n, cellObj in enumerate(rowOfCellObjects):
cellObj.value = 3
wb.save("test.xlsx")
但我正在寻找更短的表示法,例如:
from openpyxl import Workbook
from openpyxl.styles import Font
wb = Workbook()
ws = wb.active
## Without iterations
# Apply style
ws['A1':'C4'].fill = Font(name='Times New Roman')
# Assign singular value to all cells
ws['A1':'C4'].value = 3
wb.save("test.xlsx")
openpyxl
或其他模块是否提供类似的东西?
ps: 我正在使用 Python 3.5
在 Excel 中,样式 必须 应用于单个单元格,因为这是文件格式的工作原理。由于它的工作方式,openpyxl 不提供所需的功能,但可以使用 xlsxwriter.
这不是很准确。 OpenPyxel 允许将样式应用于列和行:
根据:https://openpyxl.readthedocs.io/en/stable/styles.html
Styles can also applied to columns and rows but note that this applies
only to cells created (in Excel) after the file is closed. If you want
to apply styles to entire rows and columns then you must apply the
style to each cell yourself. This is a restriction of the file format:
col = ws.column_dimensions['A']
col.font = Font(bold=True)
row = ws.row_dimensions[1]
row.font = Font(underline="single")
我想应用特定格式或为 Excel 单元格范围分配值,而不遍历每个单元格。我目前正在使用这个脚本:
from openpyxl import Workbook
from openpyxl.styles import Font
wb = Workbook()
ws = wb.active
## With iterations
# Apply style
for i, rowOfCellObjects in enumerate(ws['A1':'C4']):
for n, cellObj in enumerate(rowOfCellObjects):
cellObj.fill = Font(name='Times New Roman')
# Assign singular value to all cells
for i, rowOfCellObjects in enumerate(ws['A1':'C4']):
for n, cellObj in enumerate(rowOfCellObjects):
cellObj.value = 3
wb.save("test.xlsx")
但我正在寻找更短的表示法,例如:
from openpyxl import Workbook
from openpyxl.styles import Font
wb = Workbook()
ws = wb.active
## Without iterations
# Apply style
ws['A1':'C4'].fill = Font(name='Times New Roman')
# Assign singular value to all cells
ws['A1':'C4'].value = 3
wb.save("test.xlsx")
openpyxl
或其他模块是否提供类似的东西?
ps: 我正在使用 Python 3.5
在 Excel 中,样式 必须 应用于单个单元格,因为这是文件格式的工作原理。由于它的工作方式,openpyxl 不提供所需的功能,但可以使用 xlsxwriter.
这不是很准确。 OpenPyxel 允许将样式应用于列和行:
根据:https://openpyxl.readthedocs.io/en/stable/styles.html
Styles can also applied to columns and rows but note that this applies only to cells created (in Excel) after the file is closed. If you want to apply styles to entire rows and columns then you must apply the style to each cell yourself. This is a restriction of the file format:
col = ws.column_dimensions['A']
col.font = Font(bold=True)
row = ws.row_dimensions[1]
row.font = Font(underline="single")