[英]How to save all worksheets in Excel workbook as one text file?
I have an Excell workbook with multiple worksheets. 我有一个带有多个工作表的Excell工作簿。 I want to export the text of all worksheets to one text file.
我想将所有工作表的文本导出到一个文本文件。 I've seen multiple solutions (primarily using VBA - example below) to export each worksheet as its own text file, but have yet to find a solution to export all worksheets as one text file.
我已经看到了多种解决方案(主要使用VBA-下面的示例)将每个工作表导出为自己的文本文件,但是还没有找到一种将所有工作表导出为一个文本文件的解决方案。 Any ideas as to how to accomplish this using VBA (or perhaps Python)?
关于如何使用VBA(或Python)完成此操作的任何想法?
Sub ExportSheetsToText()
Dim xWs As Worksheet
Dim xTextFile As String
For Each xWs In Application.ActiveWorkbook.Worksheets
xWs.Copy
xTextFile = CurDir & "\" & xWs.Name & ".txt"
Application.ActiveWorkbook.SaveAs Filename:=xTextFile, FileFormat:=xlText
Application.ActiveWorkbook.Saved = True
Application.ActiveWorkbook.Close
Next
End Sub
After you generate those text files, you can easily merge many text files into one using the Windows Command Prompt
. 生成这些文本文件后,您可以使用Windows
Command Prompt
轻松地将许多文本文件合并为一个。 Suppose for instance that all your file name have some pattern in their names. 例如,假设您的所有文件名的名称都有某种模式。 ie
*.txt
but I recommend you give them some additional pattern in their name, such as temp_something.txt: 即
*.txt
但我建议您给它们添加一些其他名称,例如temp_something.txt:
xTextFile = CurDir & "\temp_" & xWs.Name & ".txt"
Then you merge them into one text file ine the command prompt like this: 然后将它们合并为一个文本文件,并在命令提示符下显示如下:
type temp_*.txt >> mergedFile.txt
or 要么
copy temp_*.txt mergedFile.txt
If you want to fully automate the operation inside the VBA routine, you can integrate the command inside it, like so: 如果要完全自动化VBA例程中的操作,可以将命令集成到其中,如下所示:
For Each xWs In Application.ActiveWorkbook.Worksheets
xWs.Copy
xTextFile = CurDir & "\temp_" & xWs.Name & ".txt"
Application.ActiveWorkbook.SaveAs Filename:=xTextFile, FileFormat:=xlText
Application.ActiveWorkbook.Saved = True
Application.ActiveWorkbook.Close
Next
Dim shl As Object: Set shl = CreateObject("WScript.shell")
shl.CurrentDirectory = CurDir
shl.Run "cmd /C copy temp_*.txt " & ThisWorkbook.name & ".txt" ' merge the temporary text files
shl.Run "cmd /C del temp_*.txt" ' clean up the temporary text files
At the end you get a text file with the same name of you workbook plus the extension .txt
. 最后,您将获得一个与您的工作簿同名的文本文件,以及扩展名
.txt
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.