简体   繁体   English

我可以将多个文本文件导入一个Excel工作表吗?

[英]Can I import multiple text files into one excel sheet?

I have one folder with multiple text files that I add one text file to every day. 我有一个包含多个文本文件的文件夹,我每天都会添加一个文本文件。 All text files are in the same format and are pipe delimited. 所有文本文件格式相同,并以管道分隔。

Is it possible to create code for excel that will automatically import the data from the multiple text files into one worksheet? 是否可以为excel创建代码,自动将多个文本文件中的数据导入到一个工作表中?

I found some code that would import all the text files from the folder, but only if I changed it all to comma delimited first. 我发现了一些代码可以导入文件夹中的所有文本文件,但前提是我将其全部更改为逗号分隔符。 Also, I could not get it to update if I added files to the folder. 另外,如果我将文件添加到文件夹,我无法更新它。

Any help would be greatly appreciated! 任何帮助将不胜感激!

A good way to handle files in general is the 'FileSystemObject'. 一般来说处理文件的好方法是'FileSystemObject'。 To make this available in VBA you need to add a reference to it: 要在VBA中使其可用,您需要添加对它的引用:

(select the Tools\\References menu. In the References dialog, select 'Microsoft Scripting Runtime') (选择Tools \\ References菜单。在References对话框中,选择'Microsoft Scripting Runtime')

The following code example will read all files in a folder, reads their content one line at a time, split each line into | 下面的代码示例将读取文件夹中的所有文件,一次读取一行内容,将每行拆分为| separated bits, and writes theses bits to the active sheet starting at cell A1, one row per line. 分离的位,并将这些位写入从单元格A1开始的有效表单,每行一行。

Sub ReadFilesIntoActiveSheet()
    Dim fso As FileSystemObject
    Dim folder As folder
    Dim file As file
    Dim FileText As TextStream
    Dim TextLine As String
    Dim Items() As String
    Dim i As Long
    Dim cl As Range

    ' Get a FileSystem object
    Set fso = New FileSystemObject

    ' get the directory you want
    Set folder = fso.GetFolder("D:\YourDirectory\")  

    ' set the starting point to write the data to
    Set cl = ActiveSheet.Cells(1, 1)

    ' Loop thru all files in the folder
    For Each file In folder.Files
        ' Open the file
        Set FileText = file.OpenAsTextStream(ForReading)

        ' Read the file one line at a time
        Do While Not FileText.AtEndOfStream
            TextLine = FileText.ReadLine

            ' Parse the line into | delimited pieces
            Items = Split(TextLine, "|")

            ' Put data on one row in active sheet
            For i = 0 To UBound(Items)
                cl.Offset(0, i).Value = Items(i)
            Next

            ' Move to next row
            Set cl = cl.Offset(1, 0)
        Loop

        ' Clean up
        FileText.Close
    Next file

    Set FileText = Nothing
    Set file = Nothing
    Set folder = Nothing
    Set fso = Nothing

End Sub

the sub is deliberately simplified to remain clear (i hope) and will need work to be made robust (eg add error handling) 故意简化sub以保持清晰(我希望)并且需要使工作变得健壮(例如添加错误处理)

Sounds like it'd be easiser to run a script to cycle thru all the files in the directory, create a new file composed of all the files' contents as new lines, and save that as a csv. 听起来更容易运行一个脚本来循环通过目录中的所有文件,创建一个由所有文件的内容组成的新文件作为新行,并将其保存为csv。 something like: 就像是:

import os

basedir='c://your_root_dir'
dest_csv="<path to wherever you want to save final csv>.csv"
dest_list=[]


for root, subs, files in  os.walk(basedir):
    for f in files:
        thisfile=open(basedir+f)
        contents=thisfile.readlines()
        dest_list.append(contents)

#all that would create a list containing the contents of all the files in the directory
#now we'll write it as a csv

f_csv=open(dest_csv,'w')
for i in range(len(dest_list)):
     f_csv.write(dest_list[i])
f_csv.close()

You could save a script like that somewhere and run it each day, then open the resulting csv in excel. 您可以在某处保存类似的脚本并每天运行它,然后在excel中打开生成的csv。 This assumes that you want to get the data from each file in a particular directory, and that all the files you need are in one directory. 这假设您希望从特定目录中的每个文件获取数据,并且您需要的所有文件都在一个目录中。

您可以使用Schema.ini( http://msdn.microsoft.com/en-us/library/ms709353VS.85.aspx ),Jet驱动程序和Union查询,运气好。

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

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