Методы Python для преобразования всех файлов Excel в папке в CSV

Чтобы преобразовать все файлы Excel в папке в формат CSV с помощью Python, вы можете использовать несколько методов. Вот несколько подходов:

Метод 1. Использование библиотеки pandas

import os
import pandas as pd
folder_path = "/path/to/folder/"
# Get all the Excel files in the folder
excel_files = [file for file in os.listdir(folder_path) if file.endswith(".xlsx") or file.endswith(".xls")]
# Convert each Excel file to CSV
for file in excel_files:
    excel_file = os.path.join(folder_path, file)
    csv_file = os.path.join(folder_path, os.path.splitext(file)[0] + ".csv")
    df = pd.read_excel(excel_file)
    df.to_csv(csv_file, index=False)

Метод 2. Использование библиотек openpyxl и csv

import os
import openpyxl
import csv
folder_path = "/path/to/folder/"
# Get all the Excel files in the folder
excel_files = [file for file in os.listdir(folder_path) if file.endswith(".xlsx") or file.endswith(".xls")]
# Convert each Excel file to CSV
for file in excel_files:
    excel_file = os.path.join(folder_path, file)
    wb = openpyxl.load_workbook(excel_file)
    sheet = wb.active
    csv_file = os.path.join(folder_path, os.path.splitext(file)[0] + ".csv")
    with open(csv_file, "w", newline="") as f:
        c = csv.writer(f)
        for r in sheet.rows:
            c.writerow([cell.value for cell in r])

Метод 3. Использование библиотек xlrd и csv

import os
import xlrd
import csv
folder_path = "/path/to/folder/"
# Get all the Excel files in the folder
excel_files = [file for file in os.listdir(folder_path) if file.endswith(".xlsx") or file.endswith(".xls")]
# Convert each Excel file to CSV
for file in excel_files:
    excel_file = os.path.join(folder_path, file)
    wb = xlrd.open_workbook(excel_file)
    sheet = wb.sheet_by_index(0)
    csv_file = os.path.join(folder_path, os.path.splitext(file)[0] + ".csv")
    with open(csv_file, "w", newline="") as f:
        c = csv.writer(f)
        for r in range(sheet.nrows):
            c.writerow(sheet.row_values(r))

Эти методы используют различные библиотеки, такие как pandas, openpyxl, xlrd и csv, для чтения файлов Excel и записи данных в файлы CSV. Вы можете выбрать метод, который лучше всего соответствует вашим требованиям.