【问题标题】:Get work sheet by name in Excel Object Model automation interface在 Excel 对象模型自动化界面中按名称获取工作表
【发布时间】:2015-10-18 01:28:13
【问题描述】:

有没有办法使用 XlsxWriter 按名称获取工作表?

import win32com.client, types, pythoncom, sys, os, string
import xlsxwriter
xlApp = win32com.client.Dispatch("Excel.Application")
for file in os.listdir("C:\Users\\Desktop\Escel"):
    if file.endswith(".xlsx"):
        fileName = file
        books = xlApp.Workbooks.Open(r"C:\\Users\\Desktop\\Escel\\" + str(fileName))
        ws = books.sheet_by_name("2015 Data")
        #ws = books.Worksheets[0]
        ws.Visible = 1
        fileName.replace(".xlsx","")  
        ws.ExportAsFixedFormat(0, r"C:\\Users\\Desktop\\PDF\\" + str(fileName) + str(".pdf"))
        books.Close(True, r"C:\\Users\\Desktop\\Escel\\" + str(fileName))

【问题讨论】:

  • AFAIK,您根本无法使用 xlsxwriter 读取 Excel 工作表,只需创建它们即可。
  • 使用 Python,this question 是否可以帮助您获取工作表名称?
  • @RBarryYoung ws = books.Worksheets[0] 似乎可以做到这一点。我想这就是 xlsxwriter 所能达到的程度。
  • AFAIK,这根本不是 xlsxwriter,而是 Excel 对象模型自动化接口。
  • 哦,好吧。对不起。这一切对我来说有点新鲜。有没有办法使用 Excel 对象模型自动化接口按名称获取工作表,然后使用 @RBarryYoung

标签: excel python-2.7 xlsxwriter


【解决方案1】:

XlsxWriter 0.8.7 现在提供了一种方法来做到这一点。例如:

worksheet = workbook.get_worksheet_by_name("Sheet1")

见: http://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name

【讨论】:

    【解决方案2】:

    例如,假设您想向 Pandas 创建的工作表添加图表或格式。即使在使用 XlsxWriter 时,您也可能需要访问工作表。诚然,这不会打开现有文件,而是在您正在创建的工作簿中找到工作表。您可以这样做:

    import numpy as np
    import pandas as pd
    from xlsxwriter.utility import xl_range
    
    writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
    workbook = writer.book
    
    df = pd.DataFrame({'Data': np.random.rand(255)})
    df.to_excel(writer, 'TEST')
    test_sheet = writer.sheets['TEST']
    
    chart = workbook.add_chart({'type': 'scatter'})
    chart.add_series(
        {
            'name': 'Rand',
            'marker': {
                'type': 'circle',
                'size': 2,
                'fill': {'color': '#008000'},
                'border': {'none': True},
            },
            'line': {'none': True},
            'categories': "=TEST!{}".format(xl_range(1, 0, 255, 0)),
            'values': "=TEST!{}".format(xl_range(1, 1, 255, 1))
        }
    )
    test_sheet.insert_chart('C1', chart)        
    writer.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多