flying-wyf

python编程快速上手之第14章实践项目参考答案(14.9)

import openpyxl,csv,os
os.chdir('C:\\Users\\Administrator\\Python35-32\\test\\excelToCSV')
for excelFile in os.listdir('.'):
  if not excelFile.endswith('.xlsx'): 
    continue
  wb = openpyxl.load_workbook(excelFile)
  wbname = excelFile.strip('.xlsx')
# Skip non-xlsx files, load the workbook object.
  for sheetName in wb.get_sheet_names():
# Loop through every sheet in the workbook.
    sheet = wb.get_sheet_by_name(sheetName)
    csvName = (wbname + '_' + sheetName +'.csv')
# Create the CSV filename from the Excel filename and sheet title.
    csvFileObj = open(os.path.join(csvName), 'w', newline='')
# Create the csv.writer object for this CSV file.
    csvWriter = csv.writer(csvFileObj)
# Loop through every row in the sheet.
    for rowNum in range(1, sheet.max_row + 1):
      rowData = [] # append each cell to this list
# Loop through each cell in the row.
      for colNum in range(1, sheet.max_column + 1):
# Append each cell's data to rowData.
          excData = sheet.cell(row=rowNum, column=colNum).value
          rowData.append(excData)
      #print(colData)
      csvWriter.writerow(rowData)
# Write the rowData list to the CSV file.
    csvFileObj.close()

 

posted on 2017-05-21 15:18  flying-wyf  阅读(205)  评论(0)    收藏  举报

导航