1
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

XLSX を PDF に変換 (pandas,FPDF)

Last updated at Posted at 2019-02-01

XLSX を pandas のデータに変換して、それを PDF に変換します。

PDFの作成には、PHP のポートの FPDF を使います。
XLSX のデータにかなり依存する変換方法です。

fpdf01.py
#! /usr/bin/python
#
#	fpdf01.py
#
#						Feb/01/2019
# ------------------------------------------------------------------
import sys
import pandas as pd
from fpdf import FPDF

# ------------------------------------------------------------------
# [2]:
def show_header_proc(pdf,array_a):
	pdf.cell(50, 10, array_a[0], 1, 0, 'C')
	pdf.cell(30, 10, array_a[1], 1, 0, 'C')
	pdf.cell(30, 10, array_a[2], 1, 0, 'C')
	pdf.cell(30, 10, array_a[3], 1, 0, 'C')
	pdf.cell(30, 10, array_a[4], 1, 2, 'C')
	pdf.cell(-140)
# ------------------------------------------------------------------
# [4]:
def show_contents_proc(pdf,df_2):
#
	for it in range(0, len(df_2)-1):
		col_ind = str(it)
		col_a = str(df_2.A.iloc[it])
		col_b = str(df_2.B.iloc[it])
		col_c = str(df_2.C.iloc[it])
		col_d = str(df_2.D.iloc[it])
		pdf.cell(50, 10, '%s' % (col_ind), 1, 0, 'C')
		pdf.cell(30, 10, '%s' % (col_a), 1, 0, 'C')
		pdf.cell(30, 10, '%s' % (col_b), 1, 0, 'C')
		pdf.cell(30, 10, '%s' % (col_c), 1, 0, 'C')
		pdf.cell(30, 10, '%s' % (col_d), 1, 2, 'C')
		pdf.cell(-140)
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
file_xlsx = sys.argv[1]
df_2 = pd.read_excel(file_xlsx)
#
pdf = FPDF()
pdf.add_page()
pdf.add_font('TakaoMincho','','/usr/share/fonts/OTF/TakaoMincho.ttf',uni=True)
pdf.set_font('TakaoMincho', '',14)
#
pdf.set_xy(0, 0)
pdf.cell(60)
pdf.cell(70, 10, 'Writing a PDF from python', 0, 2, 'C')
pdf.cell(-40)
#
array_a = ['Index Column','Col A','Col B','Col C','Col D']
show_header_proc(pdf,array_a)
#
array_a = ['No','キー','都市名','人口','改訂日']
show_header_proc(pdf,array_a)
#
show_contents_proc(pdf,df_2)
#
pdf.output('out01.pdf', 'F')
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行方法

./fpdf01.py cities.xlsx

入力データ

cities.xlsx
xlsx_feb0101.png

出力データ

out01.pdf
xlsx_feb0102.png

次の環境で動作を確認しました。

$ uname -a
Linux iwata 4.20.6-arch1-1-ARCH #1 SMP PREEMPT Thu Jan 31 08:22:01 UTC 2019 x86_64 GNU/Linux
$ python --version
Python 3.7.2
1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?