14.8 Excel到CSV的转换程序:
#!python3
import openpyxl,os,csv
filePath = input('请输入替换的文件夹路径:')
if os.path.isdir(filePath) == False:
raise Exception('filePath is invalid.')
for folderName,subfolders,filenames in os.walk(filePath):
for filename in filenames:
if filename.endswith('.xlsx') == True:
wb = openpyxl.load_workbook(os.path.join(folderName,filename))
for sheetName in wb.sheetnames:
sheet = wb[sheetName]
csvFileName = filename.replace('.xlsx','_'+sheetName+'.csv')
with open(os.path.join(folderName,csvFileName),'w',newline='') as csvFileObj:
min_row = sheet.min_row
max_row = sheet.max_row
min_column = sheet.min_column
max_column = sheet.max_column
csvWrite=csv.writer(csvFileObj)
for rowNum in range(min_row,max_row+1):
rowData = []
for colNum in range(min_column,max_column+1):
rowData.append(sheet.cell(row=rowNum,column=colNum).value)
csvWrite.writerow(rowData)