19
13

More than 5 years have passed since last update.

openpyxlで別ブックにシートをコピーする

Last updated at Posted at 2019-03-01

Introduction

この記事ではopenpyxlで別ブックにあるシートをコピーする方法を掲載しています。
openpyxlでは基本的には別ブックにあるシートを丸ごとコピーすることはできません(リンク先参照)。ですが、シートにある値であれば、コピーすることができます。

Pythonスクリプト

Pythonのコード例を以下に示します。以下の例ではfgo.xlsxのシート1の内容を読み込み、新規作成したfgo_2.xlsxのclassというシートにコピーしています。

sheet_copy.py

'''
    sheet_copy.py
    purpose: make new xlsx and copy sheet
'''

import openpyxl as xl


# set input file name
inputfile = 'fgo.xlsx'

# set output file name
outfile = 'fgo_2.xlsx'

# set output sheet title 
sheettitle = 'class'

# read tmp xlsx
wb1 = xl.load_workbook(filename=inputfile)
ws1 = wb1.worksheets[0]

# create new xlsx file
wb2 = xl.Workbook()
ws2 = wb2.worksheets[0]
ws2.title = sheettitle

# write to sheet in output file
for row in ws1:
    for cell in row:
        ws2[cell.coordinate].value = cell.value

# save target xlsx file
wb2.save(outfile)

最後の方の

# write to sheet in output file
for row in ws1:
    for cell in row:
        ws2[cell.coordinate].value = cell.value

の部分でws1(fgo.xlsxのシート1)のcellの値を、逐次的にws2(fgo_2.xlsxのclassシート)のcellに代入しています。

同様の方法を使えば、塗りつぶしの色やフォントなどの体裁もコピーできそうです。

19
13
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
19
13