繁体   English   中英

如何使用 powershell 将 xlsx 文件转换为 csv 文件?

[英]How do i convert an xlsx file into a csv file, using powershell?

如何将 xlsx 文件转换为 csv 文件并使用 Powershell 为每个单元格添加双引号?

我需要将很多文件从 .xlsx 转换为 csv。除此之外,每个单元格都必须用双引号引起来,并且必须添加一个分号分隔符。

我制作了一个 VBA 脚本来执行从 .xlsx 到 .csv 的转换并添加双引号,但每个文件需要花费多个小时。

我希望我使用 powershell 会更快。

有人知道如何在 Powershell 中重写此功能吗?

非常感谢您的帮助!

我在 VBA 中的做法:

Sub ConvertToCSV()
 Dim DestFile As String
 Dim FileNum As Integer
 Dim ColumnCount As Integer
 Dim RowCount As Long
 Dim StrFile As String


Application.ScreenUpdating = False

StrFile = Dir("C:\Users\example\*PLZ*")

Do While Len(StrFile) > 0

        Workbooks.Open ("C:\Users\example\" & StrFile)

            Range("A1").Select
            Selection.CurrentRegion.Select


            NameWithoutExtension = Left(StrFile, Len(StrFile) - 5)
            DestFile = "C:\Users\example\" & NameWithoutExtension
            FileNum = FreeFile()
            Open DestFile For Output As #FileNum


            If Err <> 0 Then
            MsgBox "Cannot open filename " & DestFile
            End
            End If
            On Error GoTo 0



                For RowCount = 1 To Selection.Rows.Count

                       ' Loop for each column in selection.
                          For ColumnCount = 1 To Selection.Columns.Count

                            OldText = Selection.Cells(RowCount, ColumnCount).Text
                            MiddleText = Replace(OldText, "\", "/")
                            NewText = Replace(MiddleText, """", "\""")

                            ' Write current cell's text to file with quotation marks.
                             Print #FileNum, """" & NewText & """";

                             ' Check if cell is in last column.
                             If ColumnCount = Selection.Columns.Count Then
                                ' If so, then write a blank line.
                                Print #FileNum,
                             Else
                                ' Otherwise, write a comma.
                                Print #FileNum, ";";
                             End If
                          ' Start next iteration of ColumnCount loop.
                          Next ColumnCount
                       ' Start next iteration of RowCount loop.
                       Next RowCount

                       ' Close destination file.
                       Close #FileNum


        ActiveWorkbook.Close


    StrFile = Dir

Loop

MsgBox ("Done")
End Sub

真的没有必要为此使用powershell,你只需要在VBA中使用正确的方法......

代码未经测试,但认为它应该可以正常工作......

Sub ConvertToCSV()
  Application.ScreenUpdating = False

  Dim StrFile As String
  StrFile = Dir("C:\Users\example\*PLZ*")

  Do While Len(StrFile) > 0
    'Open workbook
    Dim wb as workbook
    set wb = Workbooks.Open("C:\Users\example\" & StrFile)

    'Save workbook to new location
    Dim DestFile As String
    DestFile = "C:\Users\example\" & Left(StrFile, Len(StrFile) - 5)
    wb.saveAs destFile, xlFileFormat.xlCSV

    'Ensure no alerts while close
    Application.displayAlerts = false
      wb.close false
    Application.displayAlerts = true

    'Continue loop
    StrFile = Dir
  Loop
  Application.ScreenUpdating = True
End Sub

编辑:

抱歉,我没有看到需要引用字符串的要求。 可以对您的代码进行一些修补,这将使它运行得更快,关键是首先将文件转换为数组:

我试图让您的代码尽可能接近以前的代码。 请注意,您当前使用分号分隔文件...

Sub ConvertToCSV()
    Dim DestFile As String
    Dim FileNum As Integer
    Dim ColumnCount As Integer
    Dim RowCount As Long
    Dim StrFile As String


  Application.ScreenUpdating = False

  StrFile = Dir("C:\Users\example\*PLZ*")

  Do While Len(StrFile) > 0
    'Open workbook and store in variable
    Dim wb as workbook
    set wb = Workbooks.Open("C:\Users\example\" & StrFile)

    'Get data as array
    Dim r as range, v as variant
    set r = wb.ActiveSheet.Range("A1").CurrentRegion
    v = r.value2

    'Get dest path
    NameWithoutExtension = Left(StrFile, Len(StrFile) - 5)
    DestFile = "C:\Users\example\" & NameWithoutExtension
    FileNum = FreeFile()

    'Try open file
    On Error Resume Next
      Open DestFile For Output As #FileNum

      'If error then end
      If Err <> 0 Then
        MsgBox "Cannot open filename " & DestFile
        End
      End If
    On Error GoTo 0

    'Loop over array
    Dim i as long, j as long
    For i = 1 To ubound(v,1)
      For j = 1 To ubound(v,2)
        OldText = v(i,j)
        MiddleText = Replace(OldText, "\", "/")
        NewText = Replace(MiddleText, """", "\""")

        ' Write current cell's text to file with quotation marks.
        Print #FileNum, """" & NewText & """";

        ' Check if cell is in last column.
        If j = ubound(v,2) Then
          ' If so, then write a blank line.
          Print #FileNum,
        Else
          ' Otherwise, write a comma.
          Print #FileNum, ";";
        End If
      Next j 'Next column
    Next i 'Next row

    ' Close destination file.
    Close #FileNum

    'Close workbook
    wb.Close false

    'Get next file path
    StrFile = Dir    
  Loop

  MsgBox ("Done")
End Sub

注意:如果您的数据集很大,这可能会导致 out of memory 错误。 如果是,go 和 powershell。

Import-Excel .\Book1.xlsx | Export-Csv .\book1.csv

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM