簡體   English   中英

我可以將多個文本文件導入一個Excel工作表嗎?

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

我有一個包含多個文本文件的文件夾,我每天都會添加一個文本文件。 所有文本文件格式相同,並以管道分隔。

是否可以為excel創建代碼,自動將多個文本文件中的數據導入到一個工作表中?

我發現了一些代碼可以導入文件夾中的所有文本文件,但前提是我將其全部更改為逗號分隔符。 另外,如果我將文件添加到文件夾,我無法更新它。

任何幫助將不勝感激!

一般來說處理文件的好方法是'FileSystemObject'。 要在VBA中使其可用,您需要添加對它的引用:

(選擇Tools \\ References菜單。在References對話框中,選擇'Microsoft Scripting Runtime')

下面的代碼示例將讀取文件夾中的所有文件,一次讀取一行內容,將每行拆分為| 分離的位,並將這些位寫入從單元格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

故意簡化sub以保持清晰(我希望)並且需要使工作變得健壯(例如添加錯誤處理)

聽起來更容易運行一個腳本來循環通過目錄中的所有文件,創建一個由所有文件的內容組成的新文件作為新行,並將其保存為csv。 就像是:

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()

您可以在某處保存類似的腳本並每天運行它,然后在excel中打開生成的csv。 這假設您希望從特定目錄中的每個文件獲取數據,並且您需要的所有文件都在一個目錄中。

您可以使用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