[英]PowerShell: How to upload data from multiple txt files into a single xlsx or csv file
I would like to be able to use a loop that will iterate through a folder of many txt files and upload all of the data from them into a single xlsx or csv file.我希望能够使用一个循环来遍历包含许多 txt 文件的文件夹,并将其中的所有数据上传到单个 xlsx 或 csv 文件中。
The txt files are tab delimited with a few columns and include column headers. txt 文件以制表符分隔,有几列,并包括列标题。 I only want the headers to upload to the new file once so it shows up at the top but never again.
我只希望标题一次上传到新文件,以便它显示在顶部但再也不会出现。
I found the following code on another site that allows me to upload multiple files into a single one and only uploads the header once.我在另一个站点上找到了以下代码,它允许我将多个文件上传到一个文件中,并且只上传 header 一次。 The issue is that the data does not format correctly as the rows are put into a single cell when I need each point to be split up.
问题是数据格式不正确,因为当我需要拆分每个点时,将行放入单个单元格中。
$getFirstLine = $true
get-childItem "YOUR_DIRECTORY\*.txt" | foreach {
$filePath = $_
$lines = $lines = Get-Content $filePath
$linesToWrite = switch($getFirstLine) {
$true {$lines}
$false {$lines | Select -Skip 1}
}
$getFirstLine = $false
Add-Content "YOUR_DESTINATION_FILE" $linesToWrite
}
This image is an example of the txt data with the first row being the column headers: txt file data that I am trying to upload into a csv or xlsx此图像是 txt 数据的示例,第一行是列标题:我尝试上传到 csv 或 xlsx 的 txt 文件数据
If you're certain the text files all have the same format, you can treat them as tab-delimited csv files, import them and save out merged like below:如果您确定文本文件都具有相同的格式,您可以将它们视为制表符分隔的 csv 文件,导入它们并保存合并如下:
(Get-ChildItem -Path 'X:\Somewhere' -Filter '*.txt' -File).FullName |
Import-Csv -Delimiter "`t" |
Export-Csv 'X:\SomewhereElse\merged.csv' -UseCulture -NoTypeInformation
Using switch -UseCulture
means the merged csv is written out using the delimiter your local Excel expects, so when done just double-click the file to open in Excel.使用开关
-UseCulture
意味着合并的 csv 使用本地 Excel 期望的分隔符写出,因此完成后只需双击文件即可在 Excel 中打开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.