我正在尝试使用 vba 宏或 python 代码将 xlsx 文件转换为 xls。到目前为止,我可以使用以下代码获得有关在单个文件夹中转换文件的一些帮助:
Sub ProcessFiles()
Dim Filename, Pathname, saveFileName As String
Dim wb As Workbook
Dim initialDisplayAlerts As Boolean
Pathname = ""
Filename = Dir(Pathname & "*.xlsx")
initialDisplayAlerts = Application.DisplayAlerts
Application.DisplayAlerts = False
Do While Filename <> ""
Set wb = Workbooks.Open(Filename:=Pathname & Filename, _
UpdateLinks:=False)
wb.CheckCompatibility = False
saveFileName = Replace(Filename, ".xlsx", ".xls")
wb.SaveAs Filename:=Pathname & saveFileName, _
FileFormat:=xlExcel8, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
wb.Close SaveChanges:=False
Filename = Dir()
Loop
Application.DisplayAlerts = initialDisplayAlerts
End Sub
我现在尝试将其推广到给定文件夹内的所有子文件夹。
更广泛地说,我正在尝试构建一个执行以下操作的宏:
- 以批处理模式运行此命令,其中父文件夹保持不变。
- 在后台处理代码,并将所有转换后的文件放入各自的文件夹中。
例如,Max是我的主文件夹,其中可能有Med,Det,Vis,Liv子文件夹。每个子文件夹内,都会有数千个xlsx文件需要转换并放置在相同的位置父文件已存储。
请帮忙。
谢谢, 麦迪
最佳答案
您可以按如下方式在 Python 中执行此操作。这将从单个文件夹中获取所有 xlsx
文件,并使用相同的名称以 xls
格式写入它们:
import win32com.client as win32
import glob
import os
excel = win32.gencache.EnsureDispatch('Excel.Application')
for excel_filename in glob.glob(r'c:\excel_files_folder\*.xlsx'):
print excel_filename
wb = excel.Workbooks.Open(excel_filename)
wb.SaveAs(os.path.splitext(excel_filename)[0] + '.xls', FileFormat=56, ConflictResolution=2)
excel.Application.Quit()
其中 56
是要使用的格式编号,这些在 Microsoft website 中列出。 .
要在整个目录结构上执行此操作,您可以使用os.walk
,如下所示:
import win32com.client as win32
import os
excel = win32.gencache.EnsureDispatch('Excel.Application')
for dirpath, dirnames, filenames in os.walk(r'c:\excel_files_folder'):
for filename in filenames:
name, ext = os.path.splitext(filename)
if ext == '.xlsx':
wb = excel.Workbooks.Open(os.path.join(dirpath, filename))
wb.DoNotPromptForConvert = True
wb.CheckCompatibility = False
excel.DisplayAlerts = False
wb.SaveAs(os.path.join(dirpath, name + '.xls'), FileFormat=56, ConflictResolution=2)
excel.Application.Quit()
关于python - 在 Excel VBA 或 Python 中将 xlsx 文件转换为文件夹和子文件夹内的 xls,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35061363/