如何在Excel文件中使用Powershell进行区分大小写的查找和replace
我想使用Powershell在Excel文档中查找特殊字符(如希腊字母),并将其replace为HTML实体。 我的脚本如下所示:
$file = "C:\Path\To\File\test.xls" $xl = New-Object -ComObject Excel.Application $xl.Visible = $True $objWorkbook = $xl.Workbooks.Open($file) $objWorksheet = $objWorkbook.Worksheets.Item(1) $objRange = $objWorksheet.UsedRange $charArray = @( ([char]948, "δ"), ([char]916, "Δ") ) foreach ($char in $charArray){ $FindText = $char[0] $ReplaceText = $char[1] if ($objRange.find("$FindText")) { $objRange.replace("$FindText", $ReplaceText) } else {write-host "Didn't find $FindText"} }
麻烦的是, .find()
和.replace()
方法不区分大小写,因此[char]948
(δ)与小写字母δ(δ)和大写δ(Δ)字符都匹配。 结果是Excel(.xls)文件中的所有δ和Δ字符被replace为δ
。
在VBA中,Range.Find()有一个MatchCase参数,但Powershell似乎并不允许。 例如, $objRange.find("$FindText", MatchCase:=$True)
不起作用。
我也试过Powershell的-cmatch
和-creplace
命令,这是大小写敏感,但我不知道如何让这些工作在Excel范围对象$objRange
:
$objRange -creplace "$FindText", $ReplaceText
对Excel文件没有影响。
我无法将数据导出或转换为.txt或.csv,因为特殊字符无法在转换中生存。
有没有办法做到这一点?
使用PowerShell,你可以使用creplace操作符
"aAaAaA" -creplace 'a','I' IAIAIA
要replacefind,可以使用string
类中的IndexOf方法,它使用compareType
IndexOf(string value, int startIndex, int count, System.StringComparison comparisonType)
例如:
"Jean Paul".indexOF("paul", 0, [System.StringComparison]::CurrentCulture) -1 "Jean Paul".indexOF("paul", 0, [System.StringComparison]::CurrentCultureIgnoreCase) 5