Python win32客户端保存%20而不是空格

时间:2018-04-10 19:02:45

标签: python excel

我在保存pdf文件时遇到问题。该代码可以将excel文件转换为pdf,但它使用%20而不是空格保存我的所有文件。所以“沃思堡”将保存为“Fort%20Worth”。

以下是代码。感谢。

import xlwings as xw
import win32com.client

curyq = "2017Q4"

msa_list_ea = ['Albuquerque','Atlanta','Austin','Baltimore','Boston','Charlotte','Chicago','Cincinnati','Cleveland','Columbus',
        'Dallas','Dallas/Ft. Worth','Denver','Detroit','Fort Lauderdale','Fort Worth','Hartford','Houston','Indianapolis',
        'Jacksonville','Kansas City','Las Vegas','Long Island','Los Angeles','Louisville','Memphis','Miami','Milwaukee',
        'Minneapolis','Nashville','New York','Norfolk','Newark','Oakland','Orange County','Orlando','West Palm Beach',
        'Philadelphia','Phoenix','Pittsburgh','Portland','Raleigh','Richmond','Sacramento','Salt Lake City','San Antonio',
        'Riverside','San Diego','San Francisco','San Jose','Seattle','St. Louis','Tampa','Tucson','Ventura','Washington, DC']

## convert market excel EBA reports to PDF
o = win32com.client.Dispatch("Excel.Application")
o.Visible = False
for i in msa_list_ea:
    if i == "Dallas/Ft. Worth":
        i = "Dallas-Ft. Worth" 
    if i == "Newark":
        i = "Northern New Jersey"
    wb_path = r'G:/Team/EBAs/{}/Excel/{}_EBA_{}.xlsx'.format(curyq, i, curyq)

    wb = o.Workbooks.Open(wb_path)

    ws_index_list = [1] #chooses which sheet in workbook to print (counting begins at 1)

    path_to_pdf = r'G:/Team/EBAs/{}/PDF/{}_EBA_{}.pdf'.format(curyq, i, curyq) ## path to save pdf file

    wb.WorkSheets(ws_index_list).Select()

    wb.ActiveSheet.ExportAsFixedFormat(0, path_to_pdf)
    wb.Close(False)
    print("{}".format(i))

2 个答案:

答案 0 :(得分:1)

这在我的终端中正确打印,此处没有%20

我认为wb.ActiveSheet.ExportAsFixedFormat(0, path_to_pdf)中对Excel的外部调用不会尊重您的原始字符串文字

尝试添加引号:

path_to_pdf = r'"G:/Team/EBAs/{}/PDF/{}_EBA_{}.pdf"'.format(curyq, i, curyq) ## path to save pdf file

答案 1 :(得分:0)

在Windows计算机上运行类似代码时,我遇到了同样的问题。路径使用正斜杠。使用双反斜杠可以解决该问题。

要使其不是特定于操作系统,我使用os和pathlib模块正确格式化路径:

path_to_pdf = os.fspath(Path(path_to_pdf))