How to extract sheet from *.xlsm and save it as *.csv in Python?

前端 未结 3 1657
悲&欢浪女
悲&欢浪女 2021-01-05 11:03

I have a *.xlsm file which has 20 sheets in it. I want to save few sheets as *.csv (formatting loss is fine) individually. Already tried xlrd-xlwt and win32com libraries b

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-05 11:38

    You can do this easily with pandas

    1. Install pandas and xlrd dependencies by following

      • pip3 install pandas
      • pip3 install xlrd (required by pandas)
    2. Now simply read xlsm file using read_excel. Here is a demo:-

    import pandas as pd
    
    # YOU MUST PUT sheet_name=None TO READ ALL CSV FILES IN YOUR XLSM FILE
    df = pd.read_excel('YourFile.xlsm', sheet_name=None)
    
    # prints all sheets
    print(df)
    
    # prints all sheets name in an ordered dictionary
    print(df.keys())
    
    # prints first sheet name or any sheet if you know it's index
    first_sheet_name = list(df.keys())[0]
    print(first_sheet_name)
    
    # prints first sheet or any sheet if know it's name
    print(df[first_sheet_name])
    
    # export first sheet to file
    df[first_sheet_name].to_csv('FirstSheet.csv')
    
    # export all sheets 
    for sheet_name in list(df.keys()):
       df[sheet_name].to_csv(sheet_name + 'Sheet.csv')
    
    
    # USE IT IN MULTIPLE WAYS #
    

提交回复
热议问题