[Python] Convert xls* to csv
by - Thursday, January 1, 1970 at 12:00 AM


#! python3

import zipfile
import pandas as pd
from pathlib import Path
from openpyxl import load_workbook, utils

separator = '\t'
index = False
ext_res = 'csv'

if __name__ == '__main__':
    files = Path.cwd().rglob('*.xl*')
    for file in files:
        try:
            sheet_names = load_workbook(file.name, read_only=True, keep_links=False).sheetnames
            print('List name', sheet_names)
            for sheet_name in sheet_names:
                dataframe = pd.read_excel(file.name)
                dataframe.to_csv(f'{file.stem}_{sheet_name}.{ext_res}', sep=separator, index=index)

        except utils.exceptions.InvalidFileException as e:
            dataframe = pd.read_excel(file.name, engine='xlrd')
            dataframe.to_csv(f'{file.stem}.{ext_res}', sep=separator, index=index)
        except zipfile.BadZipFile as e:
            print(e)
            pass

'''

pip install pandas
pip install openpyxl

engine=
xlrd        supports old-style Excel files (.xls).
openpyxl    supports newer Excel file formats.
odf        supports OpenDocument file formats (.odf, .ods, .odt).
pyxlsb      supports Binary Excel files.
'''

Reply
Or, just open it in Excel and resave it as csv...

Reply
(October 2, 2022, 08:59 AM)tilly Wrote: Or, just open it in Excel and resave it as csv...


I agree, but this is for education bro. One day in university u will have a task for python "Make some converter" and just open Breach and u will find this and ur task its complete :D   :pomhappy:
Reply


 Users viewing this thread: [Python] Convert xls* to csv: No users currently viewing.