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?

Openpyxl: Border、値、スタイル、コラム幅のコピー

Last updated at Posted at 2024-08-08

こちらのプログラムを改造して、値、スタイル、コラム幅もコピーするようにしました。
Openpyxl: Border のコピー

プログラム

copy_borders_value.py
#! /usr/bin/python
# ---------------------------------------------------------------
#	copy_borders_value.py
#
#					Aug/08/2024
# ---------------------------------------------------------------
import sys
import openpyxl
from openpyxl.styles.borders import Border, Side
from openpyxl.utils import get_column_letter
# ---------------------------------------------------------------
def copy_cell_border(row_in,col_src,col_target):
	left_border = ws.cell(column=col_src, row=row_in).border.left.border_style
	right_border = ws.cell(column=col_src, row=row_in).border.right.border_style
	top_border = ws.cell(column=col_src, row=row_in).border.top.border_style
	bottom_border = ws.cell(column=col_src, row=row_in).border.bottom.border_style
#
#
	ws.cell(column=col_target, row=row_in).border = Border(left=Side(style=left_border), right=Side(style=right_border), top=Side(style=top_border), bottom=Side(style=bottom_border))
#
#
# ---------------------------------------------------------------
# [6]:
def copy_single_proc(ws,col_from,col_to):
	for row_in in range(2,ws.max_row):
		for it in range(7):
			no_from = col_from + it
			no_to = col_to + it
			copy_cell_border(row_in,no_from,no_to)
			col_letter_from = get_column_letter(no_from)
			col_letter_to = get_column_letter(no_to)
			column_width_A = ws.column_dimensions[col_letter_from].width
			ws.column_dimensions[col_letter_to].width = column_width_A
#
			cell_source = ws.cell(row=row_in, column=no_from)
			cell_target = ws.cell(row=row_in, column=no_to)
			cell_target.value = cell_source.value
			cell_target._style = cell_source._style
#
# ---------------------------------------------------------------
xlsx_in=sys.argv[1]
nn_in=int(sys.argv[2])
#
sys.stderr.write("xlsx_in = %s\n" % xlsx_in)
sys.stderr.write("nn_in = %d\n" % nn_in)
wb = openpyxl.load_workbook(filename=xlsx_in)
ws = wb.worksheets[0]
print(ws.max_row)
#
col_from = 10
for it in range(1,nn_in):
	jt = it -1
	col_to = 16 + jt * 6
	copy_single_proc(ws,col_from,col_to)
#
wb.save(xlsx_in)
# ---------------------------------------------------------------

実行コマンド

./copy_borders_value.py in01.xlsx 4
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?