excel - powershell excel访问无需安装Excel

标签 excel powershell

我需要能够从 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/

相关文章:

excel - 保存时出现运行时错误 1004 (Thisworkbook.save) 在一台机器上工作,而不是在另一台机器上工作

PowerShell:Visual Studio Code - 模块中的更改未反射(reflect)出来

c# - 如何在 c# powershell 模块中运行启动代码

powershell - 如何检查MS部署是否正常工作

excel - VBA - 将星期几的名称从任何语言更改为英文

vba - 在 VBA 中根据可变单元格范围设置图表源数据

vba - Excel VBA for循环中递增变量

powershell - 换行符在 powershell 中不起作用,同时替换

powershell - 保护 PowerShell 脚本中的密码

python - 将数据框写入带有标题的 excel