如何通过Powershell将DataTable导出到Excel文件? [英] How to export a DataTable into an Excel file via Powershell?

查看:69
本文介绍了如何通过Powershell将DataTable导出到Excel文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个简单快捷的选项,以通过Powershell将现有的DataTable对象导出到Excel文件中.

I was searching for a simple and fast option to export an existing DataTable-object via Powershell into an Excel file.

推荐答案

最后,我想到了这段代码.我希望它可以帮助面临相同挑战的其他人:

At the end I came up with this code. I hope it helps others with same challenge:

# get XML-schema and XML-data from the table: 
$schema = [System.IO.StringWriter]::new()
$myTable.WriteXmlSchema($schema)
$data = [System.IO.StringWriter]::new()
$myTable.WriteXml($data)

# start Excel and prepare some objects:
$xls = New-Object -Comobject Excel.Application
$xls.DisplayAlerts = $false
$xls.Visible = $false
$book = $xls.Workbooks.Add()
$sheet = $book.Worksheets[1]
$range = $sheet.Range("A1")

# import the data and save the file:
$map = $book.XmlMaps.Add($schema)
[void]$book.XmlImportXml($data, $map, $true, $range)
$book.SaveAs("c:\temp\test.xlsx", 51)
$xls.Quit()

这篇关于如何通过Powershell将DataTable导出到Excel文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆