在Excel对象模型自动化界面中按名称获取工作表

时间:2015-07-27 18:09:56

标签: excel python-2.7 xlsxwriter

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

import win32com.client, types, pythoncom, sys, os, string
import xlsxwriter
xlApp = win32com.client.Dispatch("Excel.Application")
for file in os.listdir("C:\Users\HUTRC1\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))

2 个答案:

答案 0 :(得分:3)

XlsxWriter 0.8.7现在提供了一种方法。例如:

worksheet = workbook.get_worksheet_by_name("Sheet1")

请参阅: http://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name

答案 1 :(得分:1)

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

System.exit(int)