2020年3月10日火曜日

開発環境

退屈なことはPythonにやらせよう ―ノンプログラマーにもできる自動化処理プログラミング (Al Sweigart(著)、相川 愛三(翻訳)、オライリージャパン)の第Ⅱ部(処理の自動化)、14章(PDFファイルとWordファイル文書)、14.8(演習プロジェクト)、14.8.1(ExcelからCSVへの変換)の解答を求めてみる。

コード

#!/usr/bin/env python3
import os
import csv
import openpyxl


for excel_file in os.listdir('.'):
    if not excel_file.endswith('.xlsx'):
        continue
    wb: openpyxl.Workbook = openpyxl.load_workbook(excel_file)
    for sheet_name in wb.sheetnames:
        sheet = wb[sheet_name]
        with open(excel_file[:-5] + sheet_name + '.csv', 'w') as csv_file:
            writer = csv.writer(csv_file)
            for row in range(1, sheet.max_row + 1):
                writer.writerow([sheet.cell(row=row, column=col).value
                                 for col in range(1, sheet.max_column + 1)])

入出力結果(Zsh、PowerShell、Terminal、Jupyter(IPython))

% ls *.xlsx
files.xlsx   old_multiplicationTable.xlsx
multiplicationTable.xlsx spreadsheet.xlsx*
new_multiplicationTable.xlsx
% ./xlsx2csv.py 
% ls *.xlsx    
files.xlsx   old_multiplicationTable.xlsx
multiplicationTable.xlsx spreadsheet.xlsx*
new_multiplicationTable.xlsx
% ls *.csv     
filesSheet.csv    spreadsheetL.csv
multiplicationTableSheet.csv  spreadsheetM.csv
new_multiplicationTableSheet.csv spreadsheetN.csv
old_multiplicationTableSheet.csv spreadsheetO.csv
spreadsheetA.csv   spreadsheetP.csv
spreadsheetB.csv   spreadsheetQ.csv
spreadsheetC.csv   spreadsheetR.csv
spreadsheetD.csv   spreadsheetS.csv
spreadsheetE.csv   spreadsheetT.csv
spreadsheetF.csv   spreadsheetU.csv
spreadsheetG.csv   spreadsheetV.csv
spreadsheetH.csv   spreadsheetW.csv
spreadsheetI.csv   spreadsheetX.csv
spreadsheetJ.csv   spreadsheetY.csv
spreadsheetK.csv   spreadsheetZ.csv
% head filesSheet.csv 
"#!/usr/bin/env python3
","import argparse
","import os
","import openpyxl
","from openpyxl.cell.cell import get_column_letter
","from openpyxl.styles import Font
","
","
","print('1.')
","parser = argparse.ArgumentParser()
% head multiplicationTableSheet.csv 
,1,2,3,4,5,6,7,8,9,10
1,1,2,3,4,5,6,7,8,9,10
,,,,,,,,,,
,,,,,,,,,,
2,2,4,6,8,10,12,14,16,18,20
3,3,6,9,12,15,18,21,24,27,30
4,4,8,12,16,20,24,28,32,36,40
5,5,10,15,20,25,30,35,40,45,50
6,6,12,18,24,30,36,42,48,54,60
7,7,14,21,28,35,42,49,56,63,70
% cat multiplicationTableSheet.csv 
,1,2,3,4,5,6,7,8,9,10
1,1,2,3,4,5,6,7,8,9,10
,,,,,,,,,,
,,,,,,,,,,
2,2,4,6,8,10,12,14,16,18,20
3,3,6,9,12,15,18,21,24,27,30
4,4,8,12,16,20,24,28,32,36,40
5,5,10,15,20,25,30,35,40,45,50
6,6,12,18,24,30,36,42,48,54,60
7,7,14,21,28,35,42,49,56,63,70
8,8,16,24,32,40,48,56,64,72,80
9,9,18,27,36,45,54,63,72,81,90
10,10,20,30,40,50,60,70,80,90,100
% open multiplicationTable.xlsx 
% 

0 コメント:

コメントを投稿