Python win32com 在 Excel 中换行的方法?

0 投票
1 回答
1069 浏览
提问于 2025-04-18 09:03

我需要写一个函数,能够自动调整活动Excel工作簿中所有工作表的内容换行。我已经写好了其他部分,但就是找不到这个必要的方法。有没有人知道该怎么做?

from win32com.client import Dispatch
excel = Dispatch('Excel.Application')

def main():
    WordWrapColumns()

def WordWrapColumns():
    excel.ActiveWorkbook.Save()
    filename = excel.ActiveWorkbook.FullName
    wb = excel.Workbooks.Open(filename)
    #Activate all sheets
    active_sheets = wb.Sheets.Count
    for i in range(0,active_sheets):
        excel.Worksheets(i+1).Activate()
        # Word wrap all columns in sheet
        # What command goes here????
    #Save and close workbook
    wb.Save()
    wb.Close()
    excel.Quit()

if __name__ == '__main__':
    main()

1 个回答

1

可以在网上搜索“microsoft excel interop 你的函数或常量或类”(在谷歌上有效)。在你的情况下,搜索“microsoft excel interop word wrap”会找到这个链接:Range.WrapText 属性,这说明你应该能够做类似这样的事情:

for i in range(0,active_sheets):
    ws = wb.Worksheets(i+1)
    ws.Columns.WrapText = True

撰写回答