0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

excel2pdf

Posted at
import openpyxl
import os

def find_report_sheets(excel_path):
    """
    A1セルに「報告書」が含まれるシートを探す
    """
    workbook = openpyxl.load_workbook(excel_path)
    report_sheets = []
    
    for sheet_name in workbook.sheetnames:
        sheet = workbook[sheet_name]
        if sheet['A1'].value and '報告書' in str(sheet['A1'].value):
            report_sheets.append(sheet_name)
    
    workbook.close()
    return report_sheets



excel_path = 'DisasterReport.xlsx'

# 報告書シートを探す
report_sheets = find_report_sheets(excel_path)
if not report_sheets:
    print("報告書シートが見つかりませんでした。")

# LibreOfficeを使用してPDFに変換
pdf_path = os.path.splitext(excel_path)[0] + '.pdf'
try:
    # シート名をカンマ区切りの文字列に変換
    sheet_range = ','.join(report_sheets)
    
    subprocess.run([
        'soffice',
        '--headless',
        '--convert-to', f'pdf:calc_pdf_Export:{{' +
        '"SinglePageSheets":{{"type":"boolean","value":"true"}},' +
        '"Scale":{{"type":"long","value":80}},' +
        '"ScaleToPages":{{"type":"long","value":1}},' +
        '"PageRange":{{"type":"string","value":"1-1"}},' +
        '"IsSkipEmptyPages":{{"type":"boolean","value":"false"}},' +
        '"HorizontalAlignment":{{"type":"long","value":1}},' +
        '"VerticalAlignment":{{"type":"long","value":1}},' +
        '"IsAddStream":{{"type":"boolean","value":"false"}},' +
        '"IsReduceImageResolution":{{"type":"boolean","value":"false"}},' +
        '"MaxImageResolution":{{"type":"long","value":300}},' +
        '"Margin_Top":{{"type":"long","value":10}},' +
        '"Margin_Bottom":{{"type":"long","value":10}},' +
        '"Margin_Left":{{"type":"long","value":20}},' +
        '"Margin_Right":{{"type":"long","value":10}},' +
        '"ExportSheets":{{"type":"string","value":"{sheet_range}"}}'  # シート指定を追加
        '}}',
        '--outdir', os.path.dirname(pdf_path),
        excel_path
    ], check=True)

except Exception as e:
    print(f"PDF変換中にエラーが発生しました: {e}")
0
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?