「PyhtonでExcelファイルのシートをCSVに出力する」の逆です。
# coding: utf-8
import sys
import os
import csv
import openpyxl as px
from openpyxl.utils.cell import coordinate_from_string, column_index_from_string
from openpyxl.utils import get_column_letter, column_index_from_string
def main():
args = sys.argv
exf = ''
csvf = ''
sheet = ''
add = 'A1'
if len(args) < 2:
print ('USAGE : csv2excel -csv CSVFILE -excel EXCELFILE -sheet SHEETNAME [-address A1]')
sys.exit()
for i in range(len(args)):
if args[i] == '-excel':
exf = args[i+1]
if args[i] == '-csv':
csvf = args[i+1]
if args[i] == '-sheet':
sheet = args[i+1]
if args[i] == '-address':
add = args[i+1]
csvfilepath = os.path.abspath(csvf)
if os.path.exists(csvfilepath) == False:
print ('!!!ERROR!!! CSV FILE', csvf , ' is not found')
sys.exit()
if exf == '':
exf = csvf + '.xlsx'
if sheet == '':
[sheet,ext] = os.path.splitext(csvf)
exfilepath = os.path.abspath(exf)
if os.path.exists(exfilepath) == False:
bk = px.Workbook()
sh = bk.active
sh.title = sheet
else:
bk = px.load_workbook(exfilepath)
flg = 0
for sh in bk.sheetnames:
if sh == sheet:
flg = 1
break
if flg == 0:
sh = bk.create_sheet(title=sheet)
else:
sh = bk[sheet]
a = coordinate_from_string(add)
startrow = a[1]
startcol = column_index_from_string(a[0])
print ('CSVFILE : ', csvfilepath)
print ('EXCELFILE : ', exfilepath)
print ('SHEETNAME : ', sheet)
print ('ADDRESS : ', add ,"(",startrow,",",startcol,")")
with open(csvfilepath) as fp:
reader = csv.reader(fp, delimiter=',')
irow = startrow
for row in reader:
icol = startcol
for v in row:
if str.isnumeric(v):
sh.cell(irow,icol).value = float(v)
else:
sh.cell(irow,icol).value = v
icol +=1
irow += 1
bk.save(exfilepath)
print ('FINISHED')
if __name__ == '__main__':
main()