【问题标题】:Use win32com in python to assign column width value, wrap text and add cell border to Excel file在 python 中使用 win32com 分配列宽值,换行并将单元格边框添加到 Excel 文件
【发布时间】:2022-08-24 19:56:16
【问题描述】:

我有一些代码可以将 excel 文件从 excel 转换为 PDF。虽然我知道 openpyxl 具有分配列宽值、换行和添加单元格边框的方法,但我正在寻找一种使用 win32com 模块的方法。这是因为我已经使用 win32com 打开了 Excel 文件,并且无需再次使用 openpyxl 加载 Excel 文件,可以节省执行时间。

# Import Module
from win32com import client
  
# Open Microsoft Excel
excel = client.gencache.EnsureDispatch(\'Excel.Application\')

# Make excel work in the background without appearing
excel.Visible = False
  
# Read Excel File
wb = excel.Workbooks.Open(r\'C:\\Spaced out data.xlsx\')
ws = wb.Worksheets(\'Sheet1\')

# Adjust page setup to landscape
ws.PageSetup.Orientation = 1

# Set Zoom to false because you want to fit all columns to the width of 1 page.
ws.PageSetup.Zoom = False

# Allow rows to be on multiple pages
ws.PageSetup.FitToPagesTall = False

# Fit all columns to the width of 1 page.
ws.PageSetup.FitToPagesWide = 1

# Convert into PDF File
ws.ExportAsFixedFormat(0, r\'C:\\Spaced out data.pdf\')

wb.Close(SaveChanges=False)
excel.Quit()

    标签: python excel win32com


    【解决方案1】:

    我的“去”是记录一个 Excel 宏并将其用作编写 Python 代码的基础。记录列宽更改后,启用换行并更改一些边框,我想出了这个:

    from win32com import client
    
    excel = client.gencache.EnsureDispatch('Excel.Application')
    excel.Visible = False
    wb = excel.Workbooks.Open(r'c:\users\metolone\test.xlsx')
    ws = wb.Worksheets('Sheet1')
    
    ws.Range("A:F").ColumnWidth = 10
    ws.Range("A1:F1").WrapText = True
    ws.Range("A1:F15").Borders(client.constants.xlEdgeLeft).LineStyle = client.constants.xlContinuous
    ws.Range("A1:F15").Borders(client.constants.xlEdgeLeft).Weight = client.constants.xlThick
    
    ws.PageSetup.Orientation = 1
    ws.PageSetup.Zoom = False
    ws.PageSetup.FitToPagesTall = False
    ws.PageSetup.FitToPagesWide = 1
    ws.ExportAsFixedFormat(0, r'c:\users\metolone\test.pdf')
    wb.Close(SaveChanges=False)
    excel.Quit()
    

    【讨论】:

    • 如果用户想要将列的宽度从 x 更改为 y 范围,其中 x = 1 和 y = 5 怎么办?
    【解决方案2】:

    设置特定范围(行或列)或特定列的列宽: 导入操作系统 将 win32com.client 导入为 win32 从 win32com.client 导入调度

    file = os.getcwd() + os.sep + 'Portfolio.xls'
    excel = Dispatch('Excel.Application')
    workbook = excel.Workbooks.Open(file)
    worksheet = workbook.Worksheets("Portfolio")
    
    excel.DisplayAlerts = False
    excel.Visible = False
    
    worksheet.Range("A1:A14").ColumnWidth = 25  #Specify the rows in range
    worksheet.Columns(1).ColumnWidth = 25       #Specific Column number
    worksheet.Range("B:B").ColumnWidth = 25
    
    worksheet.Columns.AutoFit()                 #Use autofit
    
    workbook.Save()
    workbook.Close()
    excel.Application.Quit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多