首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在xlsxwriter中自动设置列的宽度

如何在xlsxwriter中自动设置列的宽度
EN

Stack Overflow用户
提问于 2016-03-01 16:30:40
回答 3查看 10.7K关注 0票数 9

我一直在使用worksheet.set_column,我已经迷失了方向。是否有可能自动设置所有列的宽度?

模拟它的Python函数是什么?(仅使用xlsxwriter库):

代码语言:javascript
运行
复制
def autofit(filename, worksheet_name):
  # ???
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-03-01 16:47:56

是否有可能自动设置所有列的宽度?

不幸的是没有。

来自XlsxWriter常见问题

Q.列有"AutoFit“选项吗? 不幸的是,没有办法为AutoFit文件格式的列指定“”。此功能仅可在运行时从Excel中获得。可以在应用程序中模拟"AutoFit“,方法是跟踪写入列中数据的最大宽度,然后在最后调整列的宽度。

票数 9
EN

Stack Overflow用户

发布于 2016-03-01 16:39:59

我只知道用COM做这件事的方法。

代码语言:javascript
运行
复制
import contextlib, os, win32com.client

@contextlib.contextmanager
def load_xl_file(xlfilepath):
    ''' Open an existing Excel file using a context manager 
        `xlfilepath`: path to an existing Excel file '''
    xl = win32com.client.DispatchEx("Excel.Application")
    wb = xl.Workbooks.Open(xlfilepath)
    try:
        yield wb
    finally:
        wb.Close(SaveChanges=True)
        xl.Quit()
        xl = None # this actually ends the process 

def xlautofit(xlfilepath,skip_first_col=False):
    ''' relies on win32com.client to autofit columns on data sheets 

        remember that this is using COM so sheet numbers start at 1 (not 0), 
        so to avoid requiring the caller to remember this, we increment 

        returns full path (including dir) to file '''
    if os.path.splitext(xlfilepath)[1] not in ('.xls','.xlsx'):
        raise 
        return -1

    autofitbegcol = 1
    if skip_first_col:
        autofitbegcol += 1

    # Autofit every sheet 
    with load_xl_file(xlfilepath) as wb:
        for ws in wb.Sheets:
            autofitendcol = ws.UsedRange.Columns.Count
            ws.Range(ws.Cells(1, autofitbegcol), 
                     ws.Cells(1, autofitendcol)).EntireColumn.AutoFit()
    return xlfilepath 
票数 2
EN

Stack Overflow用户

发布于 2018-06-16 00:12:26

如果您只想要列自动安装,也许这会有帮助:

代码语言:javascript
运行
复制
import win32com.client as win32

excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'file.xlsx')
ws = wb.Worksheets("Sheet1")
ws.Columns.AutoFit()
wb.Save()
excel.Application.Quit()

更多细节请查看https://stackoverflow.com/a/33665967/1383521 :)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35728245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档