openpyxl - 调整列宽尺寸(openpyxl - adjust column width

2019-07-03 12:26发布

我有以下脚本,它是一个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)

Answer 1:

你可以估算(或使用单宽字体)来实现这一目标。 让我们假设数据是嵌套阵列状[[ 'A1', 'A2'],[ 'B1', 'B2']]

我们可以在每一列获得最大的字符。 然后将宽度设定为。 宽度是完全等宽字型的宽度(如果不是至少改变其他样式)。 即使您使用可变宽度字体是一个体面的估计。 这不会公式工作。

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

一个黑客一点,但您的报告将是更具可读性。



Answer 2:

我Bufke的回答变化。 避免了位与阵列的支化,而忽略空细胞/列。

现在固定的非字符串单元格的值。

ws = your current worksheet
dims = {}
for row in ws.rows:
    for cell in row:
        if cell.value:
            dims[cell.column] = max((dims.get(cell.column, 0), len(str(cell.value))))    
for col, value in dims.items():
    ws.column_dimensions[col].width = value


Answer 3:

更Python的方式设置,在openpyxl版本2.4.0运作至少所有列的宽度:

for column_cells in worksheet.columns:
    length = max(len(as_text(cell.value)) for cell in column_cells)
    worksheet.column_dimensions[column_cells[0].column].width = length

该as_text功能应该是该值转换成适当长度的字符串,如为Python 3:

def as_text(value):
    if value is None:
        return ""
    return str(value)


Answer 4:

我有merged_cells问题,自动调整无法正常工作,如果你有同样的问题,你可以用下面的代码解决:

for col in worksheet.columns:
    max_length = 0
    column = col[0].column # Get the column name
    for cell in col:
        if cell.coordinate in worksheet.merged_cells: # not check merge_cells
            continue
        try: # Necessary to avoid error on empty cells
            if len(str(cell.value)) > max_length:
                max_length = len(cell.value)
        except:
            pass
    adjusted_width = (max_length + 2) * 1.2
    worksheet.column_dimensions[column].width = adjusted_width


Answer 5:

上述接受的答案的略有好转,我认为是更Python(请求原谅比请示就擅自越好)

column_widths = []
for row in workSheet.iter_rows():
    for i, cell in enumerate(row):
        try:
            column_widths[i] = max(column_widths[i], len(cell.value))
        except IndexError:
            column_widths.append(len(cell.value))

for i, column_width in enumerate(column_widths):
    workSheet.column_dimensions[get_column_letter(i + 1)].width = column_width


Answer 6:

这是我的版本指@Virako的代码片段

def adjust_column_width_from_col(ws, min_row, min_col, max_col):

        column_widths = []

        for i, col in \
                enumerate(
                    ws.iter_cols(min_col=min_col, max_col=max_col, min_row=min_row)
                ):

            for cell in col:
                value = cell.value
                if value is not None:

                    if isinstance(value, str) is False:
                        value = str(value)

                    try:
                        column_widths[i] = max(column_widths[i], len(value))
                    except IndexError:
                        column_widths.append(len(value))

        for i, width in enumerate(column_widths):

            col_name = get_column_letter(min_col + i)
            value = column_widths[i] + 2
            ws.column_dimensions[col_name].width = value

以及如何使用如下所示,

adjust_column_width_from_col(ws, 1,1, ws.max_column)


Answer 7:

所有上述答案产生问题,它是COL [0] .COLUMN正在返回数量,同时worksheet.column_dimensions [柱]只接受字符,如在适当位置的列“A”,“B”,“C”。 我修改@ Virako的代码,它现在是工作的罚款。

import re
import openpyxl
..
for col in _ws.columns:
    max_lenght = 0
    print(col[0])
    col_name = re.findall('\w\d', str(col[0]))
    col_name = col_name[0]
    col_name = re.findall('\w', str(col_name))[0]
    print(col_name)
    for cell in col:
        try:
            if len(str(cell.value)) > max_lenght:
                max_lenght = len(cell.value)
        except:
            pass
    adjusted_width = (max_lenght+2)
    _ws.column_dimensions[col_name].width = adjusted_width


文章来源: openpyxl - adjust column width size