65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 Visual Basic.NET 从 Excel 电子表格中的名称创建批量或大量文件夹

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (2投票s)

2010 年 4 月 7 日

CPOL

1分钟阅读

viewsIcon

40948

这段示例代码演示了如何使用存储在 Excel 电子表格中的文件夹名称创建一系列文件夹。

引言

这段示例代码演示了如何使用存储在 Excel 电子表格中的文件夹名称创建一系列文件夹。

如何使用

  • 打开包含文件夹名称的任何 Excel 电子表格。您可以从下载的源代码中获取一个示例电子表格。

  • 选择文件夹名称并从该 Excel 电子表格中复制它们。
  • 使用 Visual Studio 2005 打开下载的源代码并运行它。应该出现以下窗体。

  • 点击“从 Excel 粘贴”。这会将 Excel 电子表格中的值粘贴到 DatagridView 中。如果未粘贴,请确保您已从 Excel 电子表格中复制了值。

  • 输入要创建文件夹的目录路径,并确保该目录存在。
  • 点击 创建文件夹 按钮。这将在指定的目录中创建文件夹。

工作原理

此示例使用了两个主要功能

  1. 使用 Clipboard 对象从 Excel 电子表格中获取目录名称值。
  2. 使用 DirectoryInfo 对象创建文件夹。

(1) 从 Excel 电子表格中获取目录名称值

VB.NET 剪贴板对象允许您从 Clipboard 对象中获取文本。以下是代码:

Dim s As String = Clipboard.GetText()
'When you get excel clipboard data as string, it will separate 
'cells with a new line character. Use this new line character 
'to split values in to an array.
Dim cells() As String = s.Split(vbNewLine)
'Now Cells() array will hold all directory names.

使用 cells() 数组构建一个 datatable 并将其赋值给 DataGridView 作为 datasource

'Create data table with directory names.
Dim DT As New DataTable()
DT.Columns.Add("Directory Name")
Dim i As Integer
'Loop through cells() array and add rows in data table.
For i = 0 To cells.Length - 1
    DT.Rows.Add(New Object() {cells(i)})
Next
DataGridView1.DataSource = DT

(2) 创建文件夹

一旦您在 DataGridView 中拥有文件夹名称,就可以使用 DirectoryInfo() 对象创建文件夹。

'Get values from DataGridView datasource to a DataTable.
Dim DT As DataTable = DataGridView1.DataSource

Dim i As Integer
'Loop through grid and get directory names.
For i = 0 To DT.Rows.Count - 1
    'Get directory name.
    Dim DirName As String = DT.Rows(i)("Directory Name").ToString()
    'Trim directory name to remove spaces from beginning or end of string.
    DirName = Trim(DirName)
    If (DirName  "") Then
        'Initialize a DirectoryInfo object with this directory.
        'txtDir is the path where directories needs to be created.
        Dim oDir As New DirectoryInfo(txtDir.Text + DirName) 
        oDir.Create()
    End If
Next

历史

  • 2010 年 4 月 7 日:初始发布
© . All rights reserved.