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?

More than 1 year has passed since last update.

xlsx を シートで分割 (python3)

0
Last updated at Posted at 2019-01-24

表示されているシートごとのファイルに xlsx を分割します。

プログラム

split_xlsx.py
#! /usr/bin/python
#
#	split_xlsx.py
#
#					Jan/24/2019
import	sys
from openpyxl import load_workbook
#
# ---------------------------------------------------------------
def sheet_pick_up_proc(wb,sheetnames,nn_sheet):
	sheet_target = sheetnames[nn_sheet]
	for sheet in sheetnames:
		if sheet != sheet_target:
			del wb[sheet]
		else:
			print(sheet_target)
#
	xlsx_out = "sheet_%d.xlsx" % nn_sheet
	wb.save(xlsx_out)
#
# ---------------------------------------------------------------
sys.stderr.write ("*** 開始 ***\n")
#
xlsx_file = sys.argv[1]
sys.stderr.write(xlsx_file + "\n")
#
wa = load_workbook (filename = xlsx_file)
#
sheetnames = wa.sheetnames
print(sheetnames)
#for sheet in sheetnames:
#	print(wa[sheet].sheet_state)
#
for icount in range(len(sheetnames)):
	sys.stderr.write("icount = %d\n" % icount)
	sheet = sheetnames[icount]
	wa = load_workbook(filename = xlsx_file)
	if wa[sheet].sheet_state == "visible":
		try:
			sheet_pick_up_proc(wa,sheetnames,icount)
		except Exception as ee:
			sys.stderr.write("*** error *** in sheet_pick_up_proc ***\n")
			sys.stderr.write(str(ee) + "\n")
#
sys.stderr.write ("*** 終了 ***\n")
# ---------------------------------------------------------------

実行方法

./split_xlsx.py in01.xlsx

次のようなファイルが作成されます。

sheet_0.xlsx
sheet_1.xlsx

確認したバージョン

$ python
Python 3.12.3 (main, Apr 10 2024, 05:33:47) [GCC 13.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import openpyxl
>>> openpyxl.__version__
'3.1.2'
0
0
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
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?