![](/img/trans.png)
[英]How to convert txt file delimited by pipe symbol to xls file in Java
[英]Convert pipe delimited txt file to xlsx
我必须将 40 多个管道分隔的 .txt 文件转换为 Excel 表(.xlsx)。 此外,所有字段在转换时都应视为文本。 以下是我发现的最有效的手动方法。 假设我将文件作为 sample1.txt 到... sampleN.txt。
1. Drag sample1.txt file to empty workbook. Then it creates new workbook with single sheet with sheet name same as sample1 copying all lines in file under column A.
2. Select column A and use text to column wizard.
3. Choose delimited file with pipe (|) delimiter and select text data type after selecting all column in next wizard tab. Then Finish.
4. File 'Save as' sample1.xlsx
录制宏后,我可以使用单个组合键执行步骤 2 到 4。 然而,“sample1”在宏中被硬编码。 因此,每次我必须适当地重命名保存的文件时。 在“另存为”期间,是否可以根据当前工作表名称获取文件名? 有没有更好更简单的方法来做这一切? 可能像批处理模式等。
我使用了一个经常用于循环遍历文件文件夹的宏。 请注意,是否会尝试使用所有文件(而不仅仅是文本文件),因此我通常会创建一个专门用于导入的文件夹。
文件夹路径在宏中硬编码(这可以更改以显示文件夹对话框。然后检查以确保路径有效,然后循环遍历每个文件执行某些操作,关闭文件并最后打印打开的文件数。
Sub process_folder()
Dim book_counter As Integer
Dim folder_path As String
Dim pWB As Workbook, sWB As Workbook, sWB_name As String
Dim pWS As Worksheet
book_counter = 0
Set pWB = ActiveWorkbook
Set pWS = pWB.ActiveSheet
folder_path = "C:\a"
folder_path = verify_folder(folder_path)
If folder_path = "NULL" Then
Exit Sub
End If
'Get first file to open
sWB_name = Dir(folder_path, vbNormal)
'Loop through files
Do While sWB_name <> ""
'Open each file
Workbooks.Open Filename:=folder_path & sWB_name
Set sWB = Workbooks(sWB_name)
'''''''''''''''''''''''''
'Do stuff here (this just prints the file name)
MsgBox (sWB.Sheets(1).Name)
'''''''''''''''''''''''''
'close file increment counter
sWB.Close (False)
sWB_name = Dir()
book_counter = book_counter + 1
Loop
'Number of files processed
MsgBox ("Number of Fragment Files processed: " & book_counter)
End Sub
Function verify_folder(path As String) As String
If path = "" Then
MsgBox ("Enter a Directory to process")
verify_folder = "NULL"
Exit Function
End If
If Not PathExists(path) Then
MsgBox ("Directory does not exist")
verify_folder = "NULL"
Exit Function
End If
If Right(path, 1) <> "\" Then
verify_folder = path & "\"
End If
End Function
Function PathExists(pName) As Boolean
On Error Resume Next
PathExists = (GetAttr(pName) And vbDirectory) = vbDirectory
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.