openpyxl-调整列宽大小 [英] openpyxl - adjust column width size

查看:556
本文介绍了openpyxl-调整列宽大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下脚本将CSV文件转换为XLSX文件,但是我的列大小非常狭窄.每次我必须用鼠标拖动它们以读取数据时.有人知道如何在openpyxl中设置列宽吗?

I have following script which is converting a CSV file to an XLSX file, but my column size is very narrow. Each time I have to drag them with mouse to read data. Does anybody know how to set column width in openpyxl?

这是我正在使用的代码.

Here is the code I am using.

#!/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)

推荐答案

您可以估算(或使用单色字体)来实现这一目标.假设数据是一个嵌套数组,例如[['a1','a2'],['b1','b2']]

You could estimate (or use a mono width font) to achieve this. Let's assume data is a nested array like [['a1','a2'],['b1','b2']]

我们可以获取每一列中的最大字符数.然后将宽度设置为该宽度.宽度正好是等宽字体的宽度(如果至少未更改其他样式).即使您使用可变宽度的字体,这也是一个不错的估计.这不适用于公式.

We can get the max characters in each column. Then set the width to that. Width is exactly the width of a monospace font (if not changing other styles at least). Even if you use a variable width font it is a decent estimation. This will not work with formulas.

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):
    worksheet.column_dimensions[get_column_letter(i+1)].width = column_width

有点骇人听闻,但您的报告将更具可读性.

A bit of a hack but your reports will be more readable.

这篇关于openpyxl-调整列宽大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆