Python- 通过一些修改从 xls 创建 pdf

Python- creating pdf from xls with some modifications

我正在尝试在 Python 中编写允许将 xls 文件转换为 pdf 的应用程序。 xls 文件有 3 列:指数、波兰兹罗提价格和欧元价格(价格不变)。我想要的是生成可打印的 pdf 标签,其中包含每个索引的所有这些信息 - 粗体索引及其下方的价格。所以基本上标签应该有大索引,这两个价格,换句话说,一行应该是一个 pdf 页面的精确大小。它还需要有简单的图形用户界面——只有两个按钮,上传文件和生成。

现在我尝试使用 openpyxl 获取所有行:

import openpyxl

wb = openpyxl.load_workbook('arkusz.xlsx')
ws = wb.get_sheet_by_name('Arkusz1')
mylist = []
for row in ws.iter_rows('A{}:C{}'.format(ws.min_row,ws.max_row)):
    for cell in row:
        mylist.append(cell.value)
print (mylist)

我得到了行,但现在我无法将其写入 pdf。我找不到任何适合我要求的库。你能为这个应用程序推荐最好的库吗?

如果您只是阅读 excel 然后创建原始 pdf,我建议您只使用 pandas.read_excel 来阅读 .xlsx 文件。

对于创建pdf部分,有几个选项,包括pydf2pdfdocumentFPDF。 FPDF 库使用起来相当简单,这就是我在本示例中使用的库。可以找到 FPDF 文档 here.

我在下面发布了一个完全可重现的示例,使用 pandas 和 fpdf(它还使用 numpy 创建示例数据框)。我在我的示例中遍历了整个数据框,但如果你愿意,你可以 select 基于索引的特定行。

import pandas as pd
import numpy as np
from fpdf import FPDF

# Creating a dataframe and saving as test.xlsx in current directory
df_1 = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
writer = pd.ExcelWriter('test.xlsx')
df_1.to_excel(writer)
writer.save()

#read in the .xlsx file just created
df_2 = pd.read_excel('test.xlsx')

#creating a pdf in called test.pdf in the current directory
pdf = FPDF()
pdf.add_page()
pdf.set_xy(0, 0)
pdf.set_font('arial', 'B', 14)
pdf.cell(60)
pdf.cell(70, 10, 'Writing a PDF from python', 0, 2, 'C')
pdf.cell(-40)
pdf.cell(50, 10, 'Index Column', 1, 0, 'C')
pdf.cell(40, 10, 'Col A', 1, 0, 'C')
pdf.cell(40, 10, 'Col B', 1, 2, 'C')
pdf.cell(-90)
pdf.set_font('arial', '', 12)
for i in range(0, len(df_2)-1):
    col_ind = str(i)
    col_a = str(df_2.A.ix[i])
    col_b = str(df_2.B.ix[i])
    pdf.cell(50, 10, '%s' % (col_ind), 1, 0, 'C')
    pdf.cell(40, 10, '%s' % (col_a), 0, 0, 'C')
    pdf.cell(40, 10, '%s' % (col_b), 0, 2, 'C')
    pdf.cell(-90)
pdf.output('test.pdf', 'F')

预期的 pdf 输出将如下所示: