xls与xlsx互转

from openpyxl import Workbook
import pandas as pd
import glob
import xlrd
import os

def xlsx_to_xls(filename,save_path):    
    df = pd.read_excel(filename) # 读取 .xlsx 文件 
    new_filename = filename[:-1]    
    new_save_path=save_path+'\\'+new_filename.split('\\')[-1]
    df.to_excel(new_save_path, index=False) # 保存为 .xls 文件


def xls_to_xlsx(filename,save_path): 
    # 打开 .xls 文件   
    workbook = xlrd.open_workbook(filename)
    sheet = workbook.sheet_by_index(0)   

    # 创建新的 .xlsx 文件
    workbook_new = Workbook()
    sheet_new = workbook_new.active
    
    # 获取表头
    header=['时间','入流','出流','水位,','库容','汛限水位','防洪高水位','校核洪水位']
    for i in range(len(header)):
        sheet_new.cell(row=1, column=i+1, value=header[i])

    # 将数据从 .xls 文件复制到 .xlsx 文件    
    for row in range(2, sheet.nrows):
        for col in range(sheet.ncols):
            sheet_new.cell(row=row, column=col+1, value=sheet.cell_value(row, col))
    
    # 保存 .xlsx 文件
    new_filename = filename.split('.')[0].split('\\')[-1]
    new_save_path=save_path+'\\'+new_filename.split('\\')[-1]+'.xlsx'
    
    workbook_new.save(new_save_path)

    
    
    
    
if __name__ == "__main__":       
    # 使用glob模块查找所有的Excel文件
    excel_files0 = glob.glob(os.path.join(folder_path, '*.xlsx'))
    excel_files1 = glob.glob(os.path.join(folder_path, '*.xls'))    
    
    
    #读取文件夹中所有的表格数据     
#     folder_path =r'C:\Users\fanfu\Desktop\xlsx'
#     save_path=r'C:\Users\fanfu\Desktop\xls'
#     for excel_file in excel_files0:
#         print(excel_file)
#         xlsx_to_xls(excel_file,save_path)
#         print('完成')
    
    
    folder_path = r'C:\Users\fanfu\Desktop\xls'
    save_path=r'C:\Users\fanfu\Desktop\xlsx'
    for excel_file in excel_files1:        
        xls_to_xlsx(excel_file,save_path)
        print('完成')
    


你可能感兴趣的:(偷偷懒,数学建模,python,开发语言)