Windows Powershell 2.0 - 如何将 ODBC 从系统 DSN 读取到 Excel 2007 工作表中

发布于 2024-09-07 23:38:20 字数 229 浏览 1 评论 0原文

我在 Excel 文档中看到了 QueryTables 集合和 ODBCConnection 对象,但没有看到如何在 powershell 中使用它们。

我想使用单个工作表创建一个新工作簿,连接到系统 DSN(不需要登录/密码),然后运行“SELECT * FROM someTable”并将结果放入工作表中。 Excel是2007年的; powershell 是 2.0; odbc 连接是系统 DSN。

谢谢

I see in the Excel documentation the QueryTables collection and ODBCConnection object, but not how to use them in powershell.

I want to create a new workbook with a single worksheet, connect to a System DSN (doesn't need login/passowrd), and run "SELECT * FROM someTable" and have the results go into the worksheet. Excel is 2007; powershell is 2.0; the odbc connection is a system DSN.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

疾风者 2024-09-14 23:38:20

对我来说,结果就像(使用 $ws 作为工作表)一样简单

$qt = $ws.QueryTables.Add("ODBC;DSN=favoriteDSN", ws.Range("A1"), "SELECT * FROM faveTable")
$qt.Refresh()
$wb.SaveAs("H:\favoriteNewFile.xlsx")

For me, it turned out to be as simple as (with $ws as a worksheet)

$qt = $ws.QueryTables.Add("ODBC;DSN=favoriteDSN", ws.Range("A1"), "SELECT * FROM faveTable")
$qt.Refresh()
$wb.SaveAs("H:\favoriteNewFile.xlsx")
残花月 2024-09-14 23:38:20

对于 Excel 部分,您可以使用带有 -COM 参数的 new-object cmdlet 来实例化 Excel 工作表:

$xl = New-Object -Com Excel.Application
$xl.Visible = $true
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$ws.Cells.Item(1,1) = 1

然后对于数据库访问,我将使用 .NET DB 访问层(PowerShell 可以相当轻松地访问 .NET)。请参阅此两部分文章(第一部分第二部分)了解详细信息。

For the Excel part, you can use the new-object cmdlet with the -COM parameter to instantiate an Excel worksheet:

$xl = New-Object -Com Excel.Application
$xl.Visible = $true
$wb = $xl.Workbooks.Add()
$ws = $wb.Worksheets.Item(1)
$ws.Cells.Item(1,1) = 1

Then for the data base access I would use a .NET DB access layer (PowerShell can access .NET rather easily). See this two part article(part one, part two) for details.

我ぃ本無心為│何有愛 2024-09-14 23:38:20

我会继续走基思走的路。
在 Excel 中录制宏并在工作表中插入数据连接以绘制表格。录制的宏中的代码将指向您使用上述方法直接从 Powershell 将表插入工作表所需的对象和方法。

I would keep going the way that Keith was going.
Record a Macro in Excel and insert a Data Connection in the worksheet to draw down your table. The code in the recorded Macro will point to the objects and methods that you need to insert the table into your worksheet, directly from Powershell, using the approach above.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文