Last active
July 24, 2024 03:24
-
-
Save CodingOctocat/15c921acb13a5b9b05dd4777af515873 to your computer and use it in GitHub Desktop.
xls2xlsx or xlsx2xls.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from enum import Enum | |
import win32com.client as win32 | |
class Overwrite(Enum): | |
ASK = 0 | |
ALWAYS = 1 | |
NEVER = 2 | |
def xls2xlsx(path: str, overwrite=Overwrite.ASK) -> str: | |
""" | |
将 xls 文件另存为 xlsx 文件。 | |
:param path: xls 文件的相对路径或绝对路径。 | |
:param overwrite: 如果 xlsx 文件已经存在该如何处理。ASK:打开 Excel 询问,ALWAYS:总是重新另存为覆盖,NEVER:从不覆盖(使用已有 xlsx 文件)。 | |
:return: xlsx 文件的绝对路径。 | |
""" | |
if not os.path.isabs(path): | |
path = os.path.abspath(path) | |
xlsx = path + 'x' | |
if os.path.exists(xlsx) and overwrite == Overwrite.NEVER: | |
return xlsx | |
excel = win32.gencache.EnsureDispatch('Excel.Application') | |
if os.path.exists(xlsx) and overwrite == Overwrite.ALWAYS: | |
os.remove(xlsx) | |
wb = excel.Workbooks.Open(path) | |
wb.Save() | |
# FileFormat = 51 is for .xlsx extension, 56 is for .xls extension. | |
wb.SaveAs(xlsx, FileFormat=51) | |
wb.Close() | |
excel.Application.Quit() | |
return xlsx | |
def xlsx2xls(path: str, overwrite=False) -> str: | |
""" | |
将 xlsx 文件另存为 xls 文件。 | |
:param path: xlsx 文件的相对路径或绝对路径。 | |
:param overwrite: 如果 xlsx 文件已经存在该如何处理。ASK:打开 Excel 询问,ALWAYS:总是重新另存为覆盖,NEVER:从不覆盖(使用已有 xls 文件)。 | |
:return: xls 文件的绝对路径。 | |
""" | |
if not os.path.isabs(path): | |
path = os.path.abspath(path) | |
xls = path[:-1] | |
if os.path.exists(xls) and overwrite == Overwrite.NEVER: | |
return xls | |
excel = win32.gencache.EnsureDispatch('Excel.Application') | |
if overwrite == Overwrite.ALWAYS: | |
os.remove(xls) | |
wb = excel.Workbooks.Open(path) | |
wb.Save() | |
# FileFormat = 51 is for .xlsx extension, 56 is for .xls extension. | |
wb.SaveAs(xls, FileFormat=51) | |
wb.Close() | |
excel.Application.Quit() | |
return xls |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment