VBscript - 转置CSV文件

时间:2014-03-25 11:56:07

标签: csv vbscript transpose

是否有人在VBscript中使用短脚本来转置矩阵(以CSV(逗号分隔值)文件形式给出)?

A, 1, 2, 3
B, 7, 5, 6

- >

A, B
1, 7
2, 5
3, 6

非常感谢提前 汤姆

2 个答案:

答案 0 :(得分:1)

如果只有两行具有相同数量的值,则可以使用Split函数将两者读入数组:

a1 = Split(FileIn.ReadLine, ",")
a2 = Split(FileIn.ReadLine, ",")

然后,迭代数组并写入每个元素:

For i = 0 To UBound(a1)
    FileOut.WriteLine a1(i) & ", " & a2(i)
Next

我假设你知道如何打开文件进行阅读和写作?

编辑:听起来你可能有不明数量的行要阅读。在这种情况下,您可以使用数组数组:

Dim a(255) ' Hold up to 255 rows. Adjust as needed. Or use ReDim Preserve to grow dynamically.
Do Until FileIn.AtEndOfStream
    a(i) = Split(FileIn.ReadLine, ",")
    i = i + 1
Loop

然后,写:

For j = 0 To UBound(a(0))

    ' Concatenate the elements into a single string...
    s = ""
    For k = 0 To i - 1
        s = s & a(k)(j) & ","
    Next

    ' Write the string without the final comma...        
    FileOut.WriteLine Left(s, Len(s) - 1)

Next

答案 1 :(得分:0)

因此,通过创建动态数组并在发现原始矩阵的新列的同时自动增加其增长,您可以非常快速地自动构建新数据结构。

Matrix Transposer

Const OutputCSV = "C:\op.csv"
Dim dt_start, WriteOutput : dt_start = Now
Dim fso : Set fso = CreateObject("Scripting.FileSystemObject")
Dim file : Set file = fso.OpenTextFile("C:\test.csv", 1, True)
Set WriteOutput = fso.OpenTextFile(OutputCSV, 8, True)
Dim fc : fc = file.ReadAll : file.close : Dim fcArray : fcArray = Split(fc, vbCrLf)
WScript.echo "Before Transpose"
WScript.echo "----------------"
WScript.echo fc
WScript.echo "----------------"
Dim opArray() : ReDim opArray(0)
For Each row In fcArray
    Dim tmp: tmp = Split(row, ",")
    For ent=0 To UBound(tmp)
        If ent  > UBound(opArray) Then
            ReDim Preserve opArray(UBound(opArray)+1)
            opArray(ent) = Trim(tmp(ent))
        Else
            If Len(opArray(ent)) > 0 Then
                opArray(ent) = opArray(ent) & "," & Trim(tmp(ent))
            Else
                opArray(ent) = Trim(tmp(ent))
            End If
        End If
    Next
Next
Dim dt_end : dt_end = Now
WScript.echo "After Transpose"
WScript.echo "----------------"
WScript.echo Join(opArray, vbCrLf)
WScript.echo "----------------"
WScript.echo "Script Execution Time (sec): " & DateDiff("s", dt_start, dt_end)
WriteOutput.Write Join(opArray, vbCrLf) : WriteOutput.Close
相关问题