【发布时间】:2020-07-28 08:39:05
【问题描述】:
如何使用 Powershell 将 xlsx 文件转换为 csv 文件并为每个单元格添加双引号?
我需要将很多文件从 .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
【问题讨论】:
-
我编辑了问题,现在更清楚了吗?
-
你听说过ImportExcel这个模块吗?这可以让你的生活更轻松...... ;-)
-
天哪...不要遍历所有单元格...只需另存为 csv...lol
ThisWorkbook.SaveAs "my\file.csv", xlFileFormat.xlCSV -
ImportExcel 描述为here。将此与 Export-csv 结合使用,相当简单。
-
您好,感谢您的回复。我将研究 ImportExcel。 @Sancarn 每个单元格都必须用双引号封装,这就是为什么不是 possible 只保存为 CSV 文件。否则解决方案会像你说的那样简单。
标签: excel vba powershell csv xlsx