Home » excel » KDB: Save 2 or More Tables to the Same Excel/CSV File (Add Header and/or Footer)?

KDB: Save 2 or More Tables to the Same Excel/CSV File (Add Header and/or Footer)?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a table that I want to export to an Excel or CSV file.

For reference, the table is called tradesFiltered.
I am exporting the table to csv using the following in KDB:

 file:filePath,"CM_RBC_Trust_",string[first exec tradeDate from trades],".csv";
  (`$file) 0: "," 0: tradesFiltered;

But now I have to add a header and footer with additional information to the csv file. As one example, I would need to do something like this in Excel where the additional information in the header is hard-coded.

Cell A1 - MILVUS
Cell A3 - Date:
Cell A5 - To:
Cell A7 - From:
Cell B3 - MM/DD/YYYY
Cell B5 - <Name>
Cell B7 - Trade Support
Cell D7 - Phone Number:
Cell E7 - 604 123 4567

And then in Cell A9, it’s the table tradesFiltered.

How can I go about doing this?

How to&Answers:

You can always hack it together using a sparse table and then appending to the csv. Not pretty:

q)trades:([]sym:10?`3;px:10?100.0;sz:10?1000);
q)template:flip`MILVUS````!((`;`Date:;`;`To:;`;`From:);(`;`$"01/29/2019";`;`Name;`;`$"Trade Support");6#`;(5#`),`$"Phone Number";(5#`),`$"604 123 4567");
q)`:file.csv 0:","0:template;
q)h:hopen`:file.csv;
q)neg[h]"";
q)neg[h]","0:trades;
q)hclose h;

A neater way might be to make the table sit to the right of the header rather than below:

q)template:flip`MILVUS``Date:``To:``From:`!(4#"";4#"";("01/29/2018";"";"";"");4#"";("Name";"";"";"");4#"";("Trade Suport";"";"Phone Number:";"604 123 4567");4#"");
q)`:file.csv 0:","0:{@[x;til[c],#[;-1]count[y]-c:count x],'y}[template;trades];