處理 Excel 文件

處理 Excel 文件

我有一些 40-50 個 Excel 文件,這些文件在前 20x25 單元格中包含有用信息,然後在這些單元格之外包含垃圾信息。一次清除所有文件中的垃圾,只保留前 20x25 單元的最簡單方法是什麼?我可以在 Windows 上使用 Powershell 執行此操作嗎?

在此輸入影像描述

答案1

恕我直言,最簡單的方法是使用 Excel 中的 VBA 巨集:

Sub CleanFiles()
' for each file in a directory
'    open it, delete all cell content around the first 20x25 cells, write it back
' 2015-10-15

    Dim path As String, aFile As String
    Dim arr As Variant

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False
    Application.EnableEvents = False

    path = "D:\TEMP\xls\"          ' must have trailing backslash
    aFile = Dir(path & "*.xls")
    Do While aFile <> ""
        Application.StatusBar = aFile
        aFile = path & aFile
        Workbooks.Open (aFile)

        ' process file content
        arr = ActiveSheet.Range("A1:Y20")
        Cells.Clear
        ActiveSheet.Range("A1:Y20") = arr

        ' save and close WB
        ActiveWorkbook.Close True, aFile
        aFile = Dir
    Loop

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    Application.EnableEvents = False
    Application.StatusBar = False
End Sub

首先,螢幕更新和自動巨集被停用。然後,掃描特定資料夾中的“*.xls”檔案並開啟每個檔案。內部保存要保留區域的內容,然後清空整個sheet,並將內容寫回sheet。關閉文件時,它會在沒有提示的情況下保存。

答案2

Get-Content file.csv | select -First 25 | Export-Csv newfile.csv如果您指的是前 20-25 行,則可以執行 a 。您可以Get-Content -Header @("a","b","c") file.csv | Select a,b,c | Export-Csv newfile.csv按順序執行 a 等操作,以選擇一直到 y,這將是您的第 25 列。不過可能有更好的方法。

相關內容