我需要能够从 Powershell 读取现有的(受密码保护的)Excel 电子表格(一个 .xlsx 文件)- 但我不想安装 Excel。我发现的每一种方法都假定 Excel 安装在运行脚本的工作站上。
我试过 Excel 查看器,但它似乎不起作用;它不会正确调用。我查看了 stackoverflow 上的其他解决方案,但它们似乎都想更新 excel 电子表格,我希望我不必走那么远。
我是否漏掉了一些明显的东西?
最佳答案
请在此处查看 Scripting Guy 的详细文章。您必须在 Powershell 脚本中使用经典的 COM ADO。
Hey, Scripting Guy! How Can I Read from Excel Without Using Excel?
相关 Powershell 代码段:
$strFileName = "C:\Data\scriptingGuys\Servers.xls"
$strSheetName = 'ServerList$'
$strProvider = "Provider=Microsoft.Jet.OLEDB.4.0"
$strDataSource = "Data Source = $strFileName"
$strExtend = "Extended Properties=Excel 8.0"
$strQuery = "Select * from [$strSheetName]"
$objConn = New-Object System.Data.OleDb.OleDbConnection("$strProvider;$strDataSource;$strExtend")
$sqlCommand = New-Object System.Data.OleDb.OleDbCommand($strQuery)
$sqlCommand.Connection = $objConn
$objConn.open()
$DataReader = $sqlCommand.ExecuteReader()
While($DataReader.read())
{
$ComputerName = $DataReader[0].Tostring()
"Querying $computerName ..."
Get-WmiObject -Class Win32_Bios -computername $ComputerName
}
$dataReader.close()
$objConn.close()
也就是说,您已经声明您的 Excel 文件受密码保护。
根据 this Microsoft Support article ,您无法使用 OLEDB 连接打开受密码保护的 Excel 文件。
来自文章:
On the Connection tab, browse to your workbook file. Ignore the "User ID" and "Password" entries, because these do not apply to an Excel connection. (You cannot open a password-protected Excel file as a data source. There is more information on this topic later in this article.)
关于excel - powershell excel访问无需安装Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20011481/