我有以下脚本将 CSV 文件转换为 XLSX 文件,但我的列大小非常窄。每次我必须用鼠标拖动它们来读取数据。有人知道如何在 openpyxl
中设置列宽吗?
这是我正在使用的代码。
#!/usr/bin/python2.6
import csv
from openpyxl import Workbook
from openpyxl.cell import get_column_letter
f = open('users_info_cvs.txt', "rU")
csv.register_dialect('colons', delimiter=':')
reader = csv.reader(f, dialect='colons')
wb = Workbook()
dest_filename = r"account_info.xlsx"
ws = wb.worksheets[0]
ws.title = "Users Account Information"
for row_index, row in enumerate(reader):
for column_index, cell in enumerate(row):
column_letter = get_column_letter((column_index + 1))
ws.cell('%s%s'%(column_letter, (row_index + 1))).value = cell
wb.save(filename = dest_filename)
最佳答案
您可以估计(或使用单宽字体)来实现这一点。假设 data 是一个嵌套数组,例如
[['a1','a2'],['b1','b2']]
我们可以得到每列的最大字符数。然后将宽度设置为该值。宽度正是等宽字体的宽度(如果至少不改变其他样式)。即使您使用可变宽度字体,这也是一个不错的估计。这不适用于公式。
from openpyxl.utils import get_column_letter
column_widths = []
for row in data:
for i, cell in enumerate(row):
if len(column_widths) > i:
if len(cell) > column_widths[i]:
column_widths[i] = len(cell)
else:
column_widths += [len(cell)]
for i, column_width in enumerate(column_widths,1): # ,1 to start at 1
worksheet.column_dimensions[get_column_letter(i)].width = column_width
有点小技巧,但您的报告将更具可读性。
关于python - openpyxl - 调整列宽大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13197574/