使用Python将.xlsx和.xls(最新版本)转换为PDF

6

在这个.doc to pdf using python链接的帮助下,我想要处理Excel (.xlsx和.xls格式)。

以下是修改后的Excel代码:

import os
from win32com import client

folder = "C:\\Oprance\\Excel\\XlsxWriter-0.5.1"
file_type = 'xlsx'
out_folder = folder + "\\PDF_excel"

os.chdir(folder)

if not os.path.exists(out_folder):
    print 'Creating output folder...'
    os.makedirs(out_folder)
    print out_folder, 'created.'
else:
    print out_folder, 'already exists.\n'

for files in os.listdir("."):
    if files.endswith(".xlsx"):
        print files

print '\n\n'

word = client.DispatchEx("Excel.Application")
for files in os.listdir("."):
    if files.endswith(".xlsx") or files.endswith('xls'):
        out_name = files.replace(file_type, r"pdf")
        in_file = os.path.abspath(folder + "\\" + files)
        out_file = os.path.abspath(out_folder + "\\" + out_name)
        doc = word.Workbooks.Open(in_file)
        print 'Exporting', out_file
        doc.SaveAs(out_file, FileFormat=56)
        doc.Close()

它显示以下错误:

>>> execfile('excel_to_pdf.py')
Creating output folder...
C:\Excel\XlsxWriter-0.5.1\PDF_excel created.
apms_trial.xlsx
~$apms_trial.xlsx

Exporting C:\Excel\XlsxWriter-0.5.1\PDF_excel\apms_trial.pdf
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "excel_to_pdf.py", line 30, in <module>
    doc = word.Workbooks.Open(in_file)
  File "<COMObject <unknown>>", line 8, in Open
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel
', u"Excel cannot open the file '~$apms_trial.xlsx' because the file format or f
ile extension is not valid. Verify that the file has not been corrupted and that
 the file extension matches the format of the file.", u'xlmain11.chm', 0, -21468
27284), None)
>>>

代码出现问题:

doc.SaveAs(out_file, FileFormat=56)

请问FileFormat应该填写什么格式呢? 麻烦帮忙解答。


也许你的Excel文件中有VisualBasic对象或奇怪的关系?你可以通过保存一个新的干净(空)Excel文件并尝试打开它来确认。如果成功了,那么当前文件就有问题。另外,你保存在哪个Excel版本中?该库在97/2004格式中可能比最新的Excel版本更好地工作。 - user1467267
@Allendar:我该如何处理Excel版本大于2004的最新版本? - eegloo
你已经测试过之前的版本是否可行了吗?要让新版本工作,你需要对那个库进行研究。也许你需要一个替代(更新)的库来支持后续版本。但我无法真正确认这些。你唯一能做的就是研究可能的解决方案。如果在Python中真的没有解决方案,你可以看看是否有Excel的命令行工具或Ruby/PHP/Perl脚本,然后从shell中调用它们。 - user1467267
@Allendar:我尝试了97-2003版本,但它无法保存为pdf格式,只能保存为xls格式。对于Word文档没有问题,但对于Excel来说是个问题。谢谢,我会继续研究这个问题。 - eegloo
你在这一行也有一个错误:out_name = files.replace(file_type, r"pdf"),因为你从未将文件类型 xls 替换为 pdf,你只替换了 xlsx,所以如果你尝试转换一个 xls 文件,它将覆盖现有的文件。 - darthbith
显示剩余3条评论
5个回答

23

xlsxwriter的链接:

https://xlsxwriter.readthedocs.org/en/latest/contents.html

借助该工具,您可以生成.xlsx.xls格式的Excel文件。

例如,Excel文件的生成名称为trial.xls

现在,如果您想生成该Excel文件的PDF,请执行以下操作:

from win32com import client
xlApp = client.Dispatch("Excel.Application")
books = xlApp.Workbooks.Open('C:\\excel\\trial.xls')
ws = books.Worksheets[0]
ws.Visible = 1
ws.ExportAsFixedFormat(0, 'C:\\excel\\trial.pdf')

3
虽然xlsxwriter是一个有用的工具,但不幸的是它无法编辑现有的xls文件,只能从头创建一个新的文件。这使得在许多情况下它变得无用。 - JeffDror
8
这是一个仅适用于Windows的解决方案吗? - elPastor

5
我也遇到了同样的问题和错误...答案是57...请看下面...
from win32com import client
import win32api

def exceltopdf(doc):
    excel = client.DispatchEx("Excel.Application")
    excel.Visible = 0

    wb = excel.Workbooks.Open(doc)
    ws = wb.Worksheets[1]

    try:
        wb.SaveAs('c:\\targetfolder\\result.pdf', FileFormat=57)
    except Exception, e:
        print "Failed to convert"
        print str(e)
    finally:
        wb.Close()
        excel.Quit()

作为ExportAsFixedFormat的替代方案...

1

另一种解决方案是在本地启动gotenberg docker容器,并通过HTTP从python传递(由libreoffice支持的)文件到容器中,然后将结果作为pdf获取。

https://github.com/gotenberg/gotenberg

LIBREOFFICE_URL = 'http://localhost:3000/forms/libreoffice/convert'
LIBREOFFICE_LANDSCAPE_URL = 'http://localhost:3000/forms/libreoffice/convert?landscape=1'


def _retry_gotenberg(url, io_bytes, post_file_name='index.html'):
    response = None
    for _ in range(5):
        response = requests.post(url, files={post_file_name: io_bytes})
        if response.status_code == 200:
            break
        logging.info('Will sleep and retry: %s %s', response.status_code, response.content)
        sleep(3)
    if not response or response.status_code != 200:
        raise RuntimeRrror(f'Bad response from doc-to-pdf: {response.status_code} {response.content}')
    return response

def process_libreoffice(io_bytes, ext: str):
    if ext in ('.doc', '.docx'):
        url = LIBREOFFICE_URL
    else:
        url = LIBREOFFICE_LANDSCAPE_URL
    response = self._retry_gotenberg(url, io_bytes, post_file_name=f'file.{ext}')
    return response.content

1
你可以使用Python在Linux上将Excel表格打印成PDF。需要运行OpenOffice作为无头服务器并使用unoconv进行配置,需要一些配置但是可行。
你可以将OO作为(服务)守护程序运行,并将其用于xls、xlsx和doc、docx的转换。

http://dag.wiee.rs/home-made/unoconv/


0

GroupDocs.Conversion Cloud SDK for Python是将Excel转换为PDF的另一种选择。这是一个付费API,但它提供每月150个免费API调用。

P.S:我是GroupDocs的开发者推广员。

# Import module
import groupdocs_conversion_cloud
from shutil import copyfile

# Get your client_id and client_key at https://dashboard.groupdocs.cloud (free registration is required).
client_id = "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx"
client_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# Create instance of the API
convert_api = groupdocs_conversion_cloud.ConvertApi.from_keys(client_id, client_key)

try:

        #Convert PDF to PNG
        # Prepare request
        request = groupdocs_conversion_cloud.ConvertDocumentDirectRequest("pdf", "C:/Temp/Book1.xlsx")

        # Convert
        result = convert_api.convert_document_direct(request)       
        copyfile(result, 'C:/Temp/Book1_output.pdf')
        print("Result {}".format(result))
        
except groupdocs_conversion_cloud.ApiException as e:
        print("Exception when calling get_supported_conversion_types: {0}".format(e.message))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接