使用Powershell从Excel提取数据

时间:2020-09-25 21:53:52

标签: powershell

sample excel image我需要从excel中的列中导出数据,并排除一些字符,然后导出到txt文件。(附加了excel示例)。基本上,我只需要在“订单”列中提取名称,然后输出到文本文件,这就是我到目前为止的内容:

#Specify the Sheet name
$SheetName = "Today Order"

# Create an Object Excel.Application using Com interface
$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $false
# Open the Excel file and save it in $WorkBook
$WorkBook = $objExcel.Workbooks.Open($FilePath)
# Load the WorkSheet 'Change Auditor Events'
$WorkSheet = $WorkBook.sheets.item($SheetName)

#====

我可以使用下面的替换命令来修剪“订单”列中不需要的字符,我只需要名称 -replace“来自” -replace“ California的订单 如何将变量分配给订单列并处理每一行,然后使用输出文件导出?还是您有其他建议?

预先感谢。

1 个答案:

答案 0 :(得分:0)

我假设您的数据在A列中。根据需要进行更正。

我用正则表达式将名称从句子中拉出来。 -Match写入魔术变量“ $ matches”

值得一提的是,使用COM对象是做到这一点的“硬”方法。 最简单的方法是另存为csv。 简单的方法是使用处理.xlsx文件的模块。

#Specify the Sheet name
$SheetName = "Today Order"
$FilePath = "C:\whatever.xlsx"

# Create an Object Excel.Application using Com interface
$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $false
# Open the Excel file and save it in $WorkBook
$WorkBook = $objExcel.Workbooks.Open($FilePath)
# Load the WorkSheet 'Change Auditor Events'
$WorkSheet = $WorkBook.sheets.item($SheetName)

$MyData = [System.Collections.Generic.List[string]]::new() #Potentially better performance than immutable array if you're running this on thousands of rows.
for($i = 2; $i -le $WorkSheet.UsedRange.Rows.Count; $i++) {
    ($Worksheet.Range("a$i").text) -match 'from (?<name>.+) in'
    $MyData.Add($Matches.name)
}

$MyData | Out-File "C:\output.txt"