【问题标题】:Python3. How to copy multiple .xlsx files into a respective .csv file?蟒蛇3。如何将多个 .xlsx 文件复制到各自的 .csv 文件中?
【发布时间】:2022-06-13 21:47:40
【问题描述】:

我有 24 个 excel 文件,我的目标是将 .xslx 数据复制到它们各自的 24 个 .csv 文件中。我已经复制了数据,但是它在 .csv 文件中创建了 10 个副本,我相信它与“for”循环有关。我尝试使用 'writerow()' 而不是 'writerows()' 但这确实有帮助。我正在尝试理解 openpyxl 及其编写器和读取器对象。

import openpyxl, os, csv
from pathlib import Path

for excelFile in os.listdir('./excelspreadsheets'):
    if excelFile.endswith('.xlsx'): # Skip non xlsx files, load the workbook object
        wb = openpyxl.load_workbook('./excelspreadsheets/' + excelFile)
        for sheetName in wb.sheetnames:

            # Loop through every sheet in the workbook
            sheet = wb[sheetName]
            sheetTitle = sheet.title

            # Create the CSV filename from the Excel filename and sheet title
            p = Path(excelFile)
            excelFileStemName = p.stem
            CsvFilename = excelFileStemName + '_' + sheetTitle + '.csv'

            # Create the csv.writer object for this CSV file
            print(f'Creating filename {CsvFilename}...')
            outputFile = open(CsvFilename, 'w', newline='')
            outputWriter = csv.writer(outputFile)

            # Create reader object for each excel sheet
            fileObj = open('./excelspreadsheets/' + excelFile)
            fileReaderObj = csv.reader(fileObj)

            # Loop through every row in the excel 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):
                    rowData.append(sheet.values)

            # write the rowData list to the CSV file. 
            for row in rowData:
                outputWriter.writerows(row)

            outputFile.close()

因此,每个新创建的 .csv 文件都会写入正确的数据,但会写入 10 次,而不是一次。

感谢任何反馈。

【问题讨论】:

  • 我猜 sheet.values 包含一个行值,所以你可以删除 colNum 循环

标签: python-3.x csv openpyxl


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 2019-09-20
  • 1970-01-01
  • 1970-01-01
  • 2018-12-31
  • 2019-11-08
  • 1970-01-01
相关资源
最近更新 更多