1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PDF文字列取得とExcel連携の自動化スクリプト

Posted at

PDF文字列取得sとExcel連携の自動化スクリプト

この記事では、Pythonを使用してPDFファイルからデータを抽出し、Excelファイルと連携するスクリプトを解説します。主にPyPDF2openpyxlを活用してます。
このコードは、図面からの拾い作業時に図面記載の文字列からオプション項目をリストアップする目的で設計されています。

スクリプト概要

このスクリプトは以下の流れで処理を行います:

  1. PDFファイルの読み込み
  2. 条件に基づくデータ抽出
  3. Excelファイルへの書き込み

必要なライブラリ

以下のライブラリを使用しています。事前にインストールしてください。

pip install PyPDF2 openpyxl pandas

コード解説

1. PDFファイルの準備

import os
desktop = os.path.join(os.path.join(os.environ["userprofile"]), "desktop")
dir_path = os.getcwd()
dir_name = os.path.basename(os.path.dirname(__file__))

if os.path.isfile(desktop + "\\図面一式.pdf"):
    zumen_path = desktop + "\\図面一式.pdf"
else:
    zumen_path = dir_path + "\\図面一式.pdf"

デスクトップまたは現在のディレクトリに存在する図面一式.pdfを取得します[1][2]。

2. PDFのテキスト抽出

from PyPDF2 import PdfFileReader

with open(zumen_path, "rb") as pdf_input:
    reader = PdfFileReader(pdf_input)
    pdf_page = reader.getNumPages()
    pdf_str_sub = "sample"
    for n in range(pdf_page):
        page = reader.getPage(n)
        pdf_str_temp = str(page.extractText())
        pdf_str_sub = pdf_str_sub + pdf_str_temp
    pdf_str = "".join(pdf_str_sub)

PdfFileReaderを使用してPDFを開き、全ページのテキストを結合しています[1][3]。

3. 条件によるデータ抽出

if "2F平面図" in pdf_str or "2F平面図" in pdf_str:
    xlsx_list = [[23016, 1]]
else:
    xlsx_list = []

テキスト内に特定の文字列が含まれているかを確認し、リストにデータを追加します。

4. オプション項目の抽出

import re
xlsx_list_option = re.findall(r"\[(.*?)\]", pdf_str)
print(xlsx_list_option)

正規表現で[ ]に囲まれた文字列を抽出します[4]。

5. Excelファイルの操作

import openpyxl as px

wb = px.load_workbook("CSVtoEXP.xlsm", read_only=False, keep_vba=True, data_only=True)
sheet = wb['Serch']

for n in range(len(xlsx_list_option)):
    sheet.cell(min_row + n, column=6).value = "オプション工事"
    sheet.cell(min_row + n, column=7).value = 1
    sheet.cell(min_row + n, column=9).value = xlsx_list_option[n]

OpenPyXLを使用してExcelファイルを操作しています[2][5]。

6. データのコピー

import pandas as pd

original_wb = pd.read_excel("CSVtoEXP original.xlsm", sheet_name="original", engine="openpyxl", header=None)
original_data = original_wb.values
dest_sheet = wb['original']

for row_idx, row in enumerate(original_data, start=1):
    for col_idx, value in enumerate(row, start=1):
        dest_sheet.cell(row=row_idx, column=col_idx).value = value

Pandasを使用して元データをコピーし、別のシートに記録します[5]。

7. 保存

wb.save(dir_path + "\\CSVtoEXP.xlsm")

最終的に処理結果を保存します。

使用例

スクリプトを実行する前に、以下を準備してください:

  • 図面一式.pdfを指定のフォルダに配置。
  • テンプレートファイルCSVtoEXP.xlsm

実行すると、Excelファイルに抽出したデータが記録されます。

注意点

  • PdfFileReaderextractTextは抽出精度に限界があるため、PDFの構造によっては別のライブラリを検討してください[1][3]。
  • Excel操作の際、テンプレートファイルのパスが正しいか確認してください[2][5]。

この記事が役に立った場合は「LGTM」をお願いします! 😊

Citations:
[1] https://reffect.co.jp/python/python-pdf-table
[2] https://qiita.com/iceblue/items/d41b9b451bc696207c5a
[3] https://qiita.com/alice37308108/items/c9859a66981956e1dad1
[4] https://hayatasu.com/python-automation-example/
[5] https://docs.aspose.com/pdf/ja/python-net/convert-pdf-to-excel/
[6] https://magazine.techacademy.jp/magazine/28694
[7] https://note.com/elemag/n/nd2d4b5adc8a5
[8] https://note.com/python_lab/n/nfe934bb639e0

1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?