Last active
March 8, 2021 14:19
-
-
Save kotoripiyopiyo/2cd6bb6b773619f21be7c45fe4e82004 to your computer and use it in GitHub Desktop.
excelシートをcsvに変換
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!usr/bin/env python3 | |
# excelをcsvに変換 | |
import openpyxl | |
import os | |
import csv | |
# csvを入れるディレクトリを作る | |
csvdir = './csvs' | |
os.makedirs(csvdir, exist_ok=True) | |
# フォルダ内のファイル名一覧を作る | |
xlsdir = './excelSpreadsheets' | |
files = os.listdir(xlsdir) | |
# ファイル名を1つづつ見ていく。.xlsxだったら以下の操作、それ以外はスキップ | |
for xlsfile in files: | |
if xlsfile.endswith('.xlsx'): | |
# エクセルファイルを読み込む | |
wb = openpyxl.load_workbook(os.path.join('excelSpreadsheets', xlsfile)) | |
# エクセルデータからシートを取り出して、csvに書き出す | |
for sheet_name in wb.sheetnames: | |
sheet_obj = wb[sheet_name] # workbookからsheet実体を取得 | |
csvname = xlsfile[:-5] + '_' + sheet_obj.title + '.csv' # csvファイル名を作成 | |
print(csvname + ' 作成中…') | |
output_csvfile = open(os.path.join(csvdir, csvname), 'w', newline='') # 書き込み先のcsvファイルを作成 | |
output_writer = csv.writer(output_csvfile) # Writerオブジェクト生成 | |
# csvに行単位で書き込む | |
row_num = sheet_obj.max_row # 書き込むべき行数を取得 | |
for i in range(row_num): | |
row_data = [] # ここに行全体のデータを入れる | |
# 行ごとにセルからデータを取り出し、row_dataに追加する | |
for cell_obj in list(sheet_obj.rows)[i]: | |
row_data.append(cell_obj.value) | |
# 作った行をcsvに書き込む | |
output_writer.writerow(row_data) | |
output_csvfile.close() | |
else: | |
continue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
テスト用のエクセルデータはこれ
https://drive.google.com/open?id=1W1jZL2GVbwhL-yeBja9hNit6RnoSMW21