【问题标题】:Recursive excel manipulation using VB.NET使用 VB.NET 的递归 excel 操作
【发布时间】:2015-10-17 21:01:29
【问题描述】:

我正在使用 Visual Studio 2015 和 VB.net,我有 2 个文件夹。
1. C:\phd\不干净 2. C:\phd\clean

在不干净的文件夹中。我有各种子文件夹和包含各种文件的子子文件夹。我想获取 unclean 的所有子文件夹和子子文件夹中的所有 .csv 文件,对其进行处理以清理它们,然后将它们输出到 C:\clean 但具有与 unclean 中相同的子文件夹结构。

到目前为止,这是我的代码...

    Imports Excel = Microsoft.Office.Interop.Excel
Imports System.IO
Class MainWindow
    Dim xl As Excel.Application = New Excel.ApplicationClass()
    Dim wb, wbTraj, wbForce As Excel.Workbook
    Dim ws, wsData, wsLeg As Excel.Worksheet
    Dim misValue As Object = System.Reflection.Missing.Value
    Dim iCol As Integer
    Dim iRow As Integer
    Dim trajEndRow, analogEndRow, analogDataRow, forceLegRowStart, forceLegRowEnd, forceDataRow, lastDataRow As Integer
    Dim cell, trajDataRangeSrc, trajDataRangeDest, trajLegSrc, trajLegDest, analogDataRange, forceDataRangeSrc, forceDataRangeDest, forceLegSrc, forceLegDest As Excel.Range
    Dim strName As String
    Dim blank As String
    Dim iIndex As Integer
    Dim strPath As String
    Dim strFile As String

    Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
        If cleanRadioButton.IsChecked = True Then
            Dim list As List(Of String) = GetFilesRecursive("C:\phd\unclean")

            ' Loop through and display each path.
            For Each path In list
                clean(path)
            Next

        Else inputRadioButton.IsChecked = True
            ' do something else
        End If
        releaseObject(ws)
        releaseObject(wsData)
        releaseObject(wsLeg)
        releaseObject(wb)
        releaseObject(wbForce)
        releaseObject(wbTraj)
        releaseObject(xl)
    End Sub

Public Shared Function GetFilesRecursive(ByVal initial As String) As List(Of String)
        ' This list stores the results.
        Dim result As New List(Of String)

        ' This stack stores the directories to process.
        Dim stack As New Stack(Of String)

        ' Add the initial directory
        stack.Push(initial)

        ' Continue processing for each stacked directory
        Do While (stack.Count > 0)
            ' Get top directory string
            Dim dir As String = stack.Pop
            Try
                ' Add all immediate file paths
                result.AddRange(Directory.GetFiles(dir, "*.csv"))

                ' Loop through all subdirectories and add them to the stack.
                Dim directoryName As String
                For Each directoryName In Directory.GetDirectories(dir)
                    stack.Push(directoryName)
                Next

            Catch ex As Exception
            End Try
        Loop

        ' Return the list
        Return result
    End Function

Private Sub clean(path)
        strPath = path
        strFile = Dir(strPath & "*.csv")
        Do While strFile <> ""
            wb = xl.Workbooks.Open(Filename:=strPath & strFile)

            'Loop through the sheets.
            For iIndex = 1 To xl.ActiveWorkbook.Worksheets.Count
                ws = xl.ActiveWorkbook.Worksheets(iIndex)

                'Loop through the columns.
                For iCol = 1 To ws.UsedRange.Columns.Count
                    'Check row 10 of this column for the char of *
                    If InStr(ws.Cells(10, iCol).Value, "*") > 0 Then
                        'We have found a column with the char of *
                        xl.DisplayAlerts = False
                        ws.Columns(iCol).EntireColumn.Delete
                        ws.Columns(iCol).EntireColumn.Delete
                        ws.Columns(iCol).EntireColumn.Delete
                        iCol = iCol - 3
                    End If
                Next iCol

            Next iIndex
            wb.SaveAs(Filename:="C:\phd\clean\" & wb.Name, FileFormat:=51)
            wb.Close(SaveChanges:=False)
            strFile = Dir()
        Loop
        MessageBox.Show("The csv files have now been cleaned.  Congrats.")
    End Sub

但是我无法让它工作,我让自己迷失了方向。谁能帮我检查一个结构,找到任何 .csv 文件,清理它,然后在 clean 文件夹下的相同文件结构中输出它并继续搜索下一个 .csv 文件??

难以置信……

谢谢

【问题讨论】:

  • 您是否分别测试了每个部分?您应该首先查看文件是否在您的列表中正确,而不仅仅是将它们复制到新位置,然后经过充分测试,添加清理代码。

标签: vb.net excel visual-studio visual-studio-2015


【解决方案1】:

如果要克隆文件夹结构,仅保存目录名称似乎是不够的。您还需要知道每个文件夹中有哪些 CSV。为此,我将保存一个List(Of FileInfo),其中将包含 CSV 文件名及其原始文件夹。收集它们:

Private myCSVList As List(Of FileInfo)

Private Sub Button_Click(sender As Object, 
      e As EventArgs) Handles Button29.Click
    myCSVList = New List(Of FileInfo)

    FindCSVs("C:\Temp")
    ' print some:
    For n As Int32 = 0 To myCSVList.Count - 1 Step 2
        Console.WriteLine(myCSVList(n).FullName)
    Next
End Sub

Private Sub FindCSVs(path As String)
    Dim di As New DirectoryInfo(path)
    ' add the csvs in THIS folder
    myCSVList.AddRange(di.EnumerateFiles("*.csv").ToArray)

    ' look for csvs in sub folders
    For Each d As DirectoryInfo In di.EnumerateDirectories
        FindCSVs(d.FullName)
    Next
End Sub

输出:

C:\Temp\capitals.csv
C:\Temp\mycsv.csv
C:\Temp\townsinfo.csv
C:\Temp\A\AA\capitals.csv
C:\Temp\A\AA\AAA\AAAA\capitals.csv
C:\Temp\B\BB\capitals.csv

现在您有了所有 CSV 的 ToDo 列表,处理它们并将它们写回新文件夹。您应该能够在存储路径上使用String.ReplaceC:\phd\unclean 更改为C:\phd\clean。如果“干净”出现在路径中的其他位置,我会包含驱动器部分以仅更改第一个外观。

如果您需要为初始列表做一些更广泛的事情,根据日期或名称等排除一些,我可能会使用另一个Sub

...
' add the csvs in this folder
myCSVList.AddRange(LoadFiles(di))

Private Function LoadFiles(di As DirectoryInfo) As FileInfo()
    Dim thisFolder = di.EnumerateFiles("*.csv").ToList
    ' ...do stuff to remove unqualified ones
    ' ...
    Return thisFolder.ToArray

End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    相关资源
    最近更新 更多