generate Excel from scott.emp

Ages ago I explained how to generate excel from the Unix command line. For instance with HTML or with XML+ZIP
To do this in Windows is way more elegant. You get your dataset from Oracle or any other source.
Then you create an Excel Object, you add content, saves, that’s all folk!
# 1) get a dataset from Oracle 
$oracle_home = (  
  gci -recurse HKLM:\SOFTWARE\Oracle  |     
    Where-Object -Property Property -eq ORACLE_HOME |          
      Where-Object -Property PSChildName -Match KEY |           
        get-itemproperty -name ORACLE_HOME  ).oracle_home;
'[INFO] '+$oracle_home;
Add-Type -Path ($oracle_home+'\ODP.NET\bin\4\Oracle.DataAccess.dll');
$conn = New-Object Oracle.DataAccess.Client.OracleConnection('User Id=/;Password=;Data Source=DB01');
$conn.open();
$dataset = New-Object Data.dataset
(New-Object Oracle.DataAccess.Client.OracleDataAdapter("select * from emp",$conn)).fill($dataset)
$conn.close();
$conn.dispose();
# 2) get a ComObject from Excel
$excel = New-Object -ComObject excel.application
$excel.visible = $False
$wb = $excel.Workbooks.Add()
$ws= $wb.Worksheets.Item(1)
$ws.Name = "Data Set"
$row=1
$col=1
foreach ($colname in $dataset.Tables[0].Columns.ColumnName){
  $ws.Cells.Item($row,$col).Font.Bold=$True
  $ws.Cells.Item($row,$col) = $colname 
  $col++
}
foreach ($datarow in $dataset.Tables[0].rows) {
  $row++
  $col=1
  foreach ($item in  $datarow.itemarray){
    $ws.Cells.Item($row,$col) = $item
    $col++
  }
}
$excel.DisplayAlerts = 'False' 
$wb.SaveAs("C:\TEMP\ora.xlsx")  
$wb.Close()
$excel.Quit()
EMPNO ENAME JOB DEPTNO
7788 SCOTT ANALYST 20
7839 KING PRESIDENT 10

Leave a Reply

Your email address will not be published.