【问题标题】:How to export a DataTable into an Excel file via Powershell?如何通过 Powershell 将 DataTable 导出到 Excel 文件中?
【发布时间】:2023-04-05 11:45:01
【问题描述】:

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

【问题讨论】:

    标签: excel powershell datatable


    【解决方案1】:

    最后我想出了这段代码。我希望它可以帮助其他面临同样挑战的人:

    # 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 模块 ImportExcel。我认为这会让你的生活更轻松,并且不需要安装 Excel。当您想在没有安装办公室的服务器上运行某些任务时,这会派上用场。 ;-)
    猜你喜欢
    • 2016-01-15
    • 2018-12-11
    • 2011-12-12
    • 1970-01-01
    • 2016-03-29
    • 2012-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多