简体   繁体   中英

Export DataTable to Excel using PowerShell

I have a function to create System.Data.Datatables from a simple input of TableName and ColumnName-Array. After filling the tables I want to add them to a dataset and export this one into an excel document.

The code below does that, however in the export to excel there is one bit that I find a bit unelegant. Every table will have to be exported into a csv and then reimported to excel.

Is there a better cleaner way to use DataTables directly in Excel?

Function MakeTable ($TableName, $ColumnArray)
{
    $btab = New-Object System.Data.DataTable("$TableName")
    foreach($Col in $ColumnArray)
    {
        $MCol = New-Object System.Data.DataColumn $Col;
        $btab.Columns.Add($MCol)
    }
    return , $btab
}

function DataSetToExcel ($Ds, $workdirectory)
{
    $excel = New-Object -ComObject excel.application 
    $workbook = $excel.Workbooks.Add(1)
    $i = 0
    for($DsIndex=0;$DsIndex -lt $ds.Tables.Count;$DsIndex++)
    {
        $Table = $ds.tables[$Dsindex]
        if($Dsindex -ne 0)
        {
            $workbook.worksheets.Add() | Out-Null #Erstellt neues Arbeitsblatt
        }
        $Table | Export-Csv "$workdirectory\input.csv" -Encoding UTF8 -NoTypeInformation -Force -Delimiter ";"
        $inputCSV = "C:\Temp\Test\input.csv"
        $worksheet = $workbook.worksheets.Item(1)
        $worksheet.Name = $Table.TableName
        $TxtConnector = ("TEXT;" + $inputCSV)
        $Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
        $query = $worksheet.QueryTables.item($Connector.name)
        $query.TextFileOtherDelimiter = $Excel.Application.International(5)
        $query.TextFileParseType  = 1
        $query.AdjustColumnWidth = 1
        $query.Refresh() | Out-Null
        $query.Delete()
    }
    $outputXLSX = "$workdirectory\output.xlsx"
    $Workbook.SaveAs($outputXLSX,51)
    $excel.Quit()
}

function MakeTestTable ($TableName)
{
    $TestTable = MakeTable $TableName @("A","B")
    for($i=0;$i -lt 10; $i++)
    {
        $aRow = $TestTable.NewRow()
        $aRow["A"] = (10-$i).ToString()
        $aRow["B"] = $i.ToString()
        $TestTable.Rows.Add($aRow)
    }
    return , $TestTable
}

$db = New-Object System.Data.DataSet
for($cx=0;$cx -lt 10;$cx++)
{
    $tab1 = MakeTestTable "$cx"    
    $db.Tables.Add($tab1)
}
DataSetToExcel $db "C:\Temp\Test"

Check out my PowerShell Excel Module on Github . You can also grab it from the PowerShell Gallery.

It also works directly with CSV format using Import-Csv or ConvertFrom-Csv (basically any PowerShell object array).

function New-Person {

    param($First,$Last)

    $row=$dataTable.NewRow()
    $row["First"]=$First
    $row["Last"]=$Last
    $dataTable.Rows.Add($row)
}

$dataTable = New-Object System.Data.DataTable("Test")
$dataTable.Columns.Add((New-Object System.Data.DataColumn "First"))
$dataTable.Columns.Add((New-Object System.Data.DataColumn "Last"))

New-Person John Doe
New-Person Tom Doe
New-Person Jane Doe
New-Person Mary Doe

$dataTable | 
    Select First, Last | 
    Export-Excel c:\temp\people.xlsx -AutoSize -Show

在此处输入图片说明

Since you tagged this with C#, If you have excel on the computer this will be run on, you can use the interop library. I used it for a project I did, using code I found in this SO question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM