如何将一系列行从excel复制到txt文件

时间:2016-05-25 13:28:24

标签: excel powershell

我正在慢慢使用Power shell。我有一些excel文件(500+)有一个列公式,我想保存在一个新的'.txt'文件中。我已经创建了一个脚本,可以在给定的文件夹上逐个查找文件。我现在的问题是如何将一系列列从excel复制到文本文件。

这是我一直在做的事情:

#Set the start and end range of the Formula column
$NewMax = $sheet.UsedRange.Rows.Count

$FormulaRange = $Sheet.range("G5:G$NewMax")
$FormulaRange.Copy() | out-null

2 个答案:

答案 0 :(得分:0)

您可以将数据粘贴到新的Excel文件中,然后将其另存为.txt。

在你之后:

$FormulaRange.Copy()

这样做:

$wb = $app.Workbooks.Add()
$ws = $wb.Worksheets(1)
$ws.Paste()
$app.DisplayAlerts = $False
$wb.SaveAs("C:\Users\admin\Desktop\Book2.txt", -4158) # xlText
$wb.Close($False)
$app.DisplayAlerts = $True

答案 1 :(得分:0)

经过一些谷歌搜索和测试,这是我登陆的解决方案:

#Set the start and end range of the Formula column
$NewMax = $sheet.UsedRange.Rows.Count

$FormulaRange = $Sheet.range("AQ6:AQ$NewMax")
$FormulaRange | select text | Export-Csv "c:\\output\sample.txt" -NoTypeInformation
(Get-Content "c:\\output\sample.txt") | % {$_ -replace '"', ""} | out-file -FilePath "c:\\output\sample.txt" -Force -Encoding ascii

首先,我将所选范围导出到csv文件中,该文件以.txt扩展名保存。然后我使用replace函数删除了每行的引号。