我一直在使用worksheet.set_column
,我已经迷失了方向。是否有可能自动设置所有列的宽度?
模拟它的Python函数是什么?(仅使用xlsxwriter
库):
def autofit(filename, worksheet_name):
# ???
发布于 2016-03-01 16:47:56
是否有可能自动设置所有列的宽度?
不幸的是没有。
Q.列有"AutoFit“选项吗? 不幸的是,没有办法为AutoFit文件格式的列指定“”。此功能仅可在运行时从Excel中获得。可以在应用程序中模拟"AutoFit“,方法是跟踪写入列中数据的最大宽度,然后在最后调整列的宽度。
发布于 2016-03-01 16:39:59
我只知道用COM做这件事的方法。
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
发布于 2018-06-16 00:12:26
如果您只想要列自动安装,也许这会有帮助:
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/questions/35728245
复制相似问题