Glowie
Glowie

Reputation: 2309

Export SQL output to excel sheet

I would like to output sql output to an excel file, and a sheet that I give a name to, i.e. not "Sheet1". How do I even begin code this?

Below is current code that reads sql output

$sql_output = @()
while ($rdr.read()){
    $sql_output += [PSCustomObject][Ordered]@{
        Col1=$rdr.GetValue(0)
        Col2=$rdr.GetValue(1)
        Col3=$rdr.GetValue(2)
        Col4=$rdr.GetValue(3)
        Col5=$rdr.GetValue(4)
    }
    $count=$count + 1
}

Then exports to csv

$sql_output | Export-CSV "D:\Script\Network_Threat_Protection.csv" -NoTypeInfo -Append

I would eventually like this powershell script to read multiple sql queries and output it to different sheets within excel, but let me get the jist of exporting to excel first ....

Upvotes: 0

Views: 2959

Answers (2)

Godly Mathew
Godly Mathew

Reputation: 21

you can use CPPLUS library for exporting tables to excel sheets..

private DataTable GetData(string tableName)
    {
        using (SqlConnection sqlCon = new SqlConnection(connectionString))
        {
            SqlCommand sqlCommand = new SqlCommand("SELECT * FROM " + tableName, sqlCon);
            sqlCon.Open();
            var reader = sqlCommand.ExecuteReader();

            DataTable dt = new DataTable();
            dt.Load(reader);
            return dt;
        }
    }

private void SaveExcel(DataTable dataTable, string newFile)
    {
        using (ExcelPackage pck = new ExcelPackage())
        {
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add(newFile);
            ws.Cells["A1"].LoadFromDataTable(dataTable, true);
            pck.SaveAs( new System.IO.FileInfo("d:\\Export\\" + newFile + ".xlsx"));
        }
    }

Download Source

Upvotes: 0

Malk
Malk

Reputation: 12003

Export-CSV does not generate an Excel file. It generates a comma delimited text file that usually is set to open with Excel. Being a CSV file there is no knowledge of multiple sheets or dataset properties like sheetnames, for that you will need to use the Excel comobject (and all of its nuances).

Here is a basic example of writing a real Excel file:

$a = New-Object -com Excel.Application
$a.Visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item(1,1) = "A value in cell A1."
$b.SaveAs("C:\Scripts\Test.xls")
$a.Quit()

What you are trying to do is not new. There are a lot of scripts on the internet for this task. Microsoft's Script Center is a good place to find powershell scripts. Here is one that seems to do what you want.

Upvotes: 1

Related Questions