【python辦公自動化】openpyxl如何操做xls文件——把xls文件另存爲xlsx文件

前言

Openpyxl 在處理起excel表格是很是方便的。然而,openpyxl只支持xlsx文件的處理,並不能支持xls文件。又不想換第三方庫,又想處理xls文件,因而想了個折中的方法,那就是將xls文件轉換成xlsx文件。再用openpyxl進行處理。python

代碼以下:

def xls2xlsx(file_name):
    """
    將xls文件另存爲xlsx文件
    
    :param file_name: 要轉換的文件路徑
    :returns: new_excel_file_path 返回新的xlsx文件的路徑
    """
    excel_file_path = file_name
    import win32com.client
    excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
    wb = excel.Workbooks.Open(excel_file_path)

    new_excel_file_path = r"{old_file_path}x".format(old_file_path=excel_file_path)
    if os.path.exists(new_excel_file_path):  # 先刪掉新複製的文件
        os.remove(new_excel_file_path)
    wb.SaveAs(new_excel_file_path, FileFormat=51)# 51 表示的是xlsx格式
    wb.Close()
    excel.Application.Quit()
    return new_excel_file_path

該函數在調用以後返回新生成的xlsx文件的路徑函數

把新生成的文件再用openpyxl庫進行處理。ui

相關文章
相關標籤/搜索