1. 程式人生 > 其它 >xls批量轉換為xlsx格式檔案

xls批量轉換為xlsx格式檔案

由於使用的PHP庫解析xls格式檔案有問題,而將xls格式轉換為xlsx格式就可以解析,考慮到xls檔案有很多,需要使用批量轉換檔案的方法,本文介紹兩種方法。

目錄

方法1:Python pandas庫

使用Python pandas庫的to_excel方法來另存為xlsx格式。

考慮到Excel檔案一般有多個工作表,需要都讀出來然後儲存。下面直接給出程式碼:

import glob
import os
import time
import pandas as pd

class excelConvert():

    def __init__(self):
        self.path = os.getcwd()  # 當前工作路徑
        xlsxdirname = "xlsx"
        xlsxpath = os.path.join(self.path, xlsxdirname)

        if not os.path.exists(xlsxpath):
            print(f"建立資料夾: {xlsxdirname}")
            os.makedirs(xlsxpath)
        self.xlsxpath = xlsxpath

    def batch_convert(self):
        xls_files = glob.glob(self.path + "/*.xls")
        if len(xls_files) != 0:
            print('當前目錄下的xls格式檔案:')
            for file in xls_files:
                print(os.path.basename(file))

                fname, _ = os.path.splitext(file)
                basename = os.path.basename(fname)
                xlsxpathname = os.path.join(self.xlsxpath, basename)
                self.saveasxlsx(file, xlsxpathname)
        else:
            print('該目錄下無xls格式檔案,即將退出...')
            time.sleep(2)
            os._exit(0)

    def saveasxlsx(self, xlspath, xlsxpath):
        writer = pd.ExcelWriter(xlsxpath + '.xlsx')
        datas = pd.read_excel(xlspath,sheet_name=None)
        for sheetname, values in datas.items():
            data = pd.DataFrame(values)
            data.to_excel(writer, sheet_name=sheetname)
        writer.save()
        writer.close()

if __name__=='__main__':
    excel = excelConvert()
    excel.batch_convert()

使用上述程式碼無法保留原Excel檔案中的單元格樣式,接下來介紹使用VBA程式碼進行轉換。

方法2:VBA批量轉換

使用VBA程式碼進行批量轉換,程式碼來源:https://www.extendoffice.com/documents/excel/1349-excel-batch-convert-xls-to-xlsx.html

開啟Excel 2007或者以上版本,ALT + F11 開啟 Microsoft Visual Basic for Applications視窗,點選 插入-> 模組,會開啟程式碼視窗。

或者右鍵點選工作表,選擇【檢視程式碼】:

輸入以下程式碼:

Sub ConvertToXlsx()
'Updateby Extendoffice
Dim strPath As String
Dim strFile As String
Dim xWbk As Workbook
Dim xSFD, xRFD As FileDialog
Dim xSPath As String
Dim xRPath As String
Set xSFD = Application.FileDialog(msoFileDialogFolderPicker)
With xSFD
.Title = "Please select the folder contains the xls files:"
.InitialFileName = "C:\"
End With
If xSFD.Show <> -1 Then Exit Sub
xSPath = xSFD.SelectedItems.Item(1)
Set xRFD = Application.FileDialog(msoFileDialogFolderPicker)
With xRFD
.Title = "Please select a folder for outputting the new files:"
.InitialFileName = "C:\"
End With
If xRFD.Show <> -1 Then Exit Sub
xRPath = xRFD.SelectedItems.Item(1) & "\"
strPath = xSPath & "\"
strFile = Dir(strPath & "*.xls")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Do While strFile <> ""
If Right(strFile, 3) = "xls" Then
Set xWbk = Workbooks.Open(Filename:=strPath & strFile)
xWbk.SaveAs Filename:=xRPath & strFile & "x", _
FileFormat:=xlOpenXMLWorkbook
xWbk.Close SaveChanges:=False
End If
strFile = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

點選F5執行,選擇xls檔案目錄和儲存xlsx檔案的目錄,然後會進行批量轉換。

--THE END--

逃離是事實,但我沒有背叛。——劉慈欣《三體2:黑暗森林》