Exporting a file to CSV on the IFS

Log in to save
CPYTOIMPF FROMFILE(PRODLIB/ITEMS)                +
          TOSTMF('/home/export/items.csv')       +
          MBROPT(*REPLACE)                       +
          STMFCCSID(1208)                        +
          RCDDLM(*CRLF)                          +
          DTAFMT(*DLM)                           +
          STRDLM(*NONE)                          +
          FLDDLM(';')

To include column names as the first row, add ADDCOLNAM(*SQL).

Example: exporting a selection, not the whole file

CPYTOIMPF copies an entire file. When only some columns are wanted, or only one region's rows, the way is not to filter afterwards in Excel: it is to hand the command an object that already holds what is needed.

A view in QTEMP costs nothing and disappears by itself at end of job:

CREATE VIEW QTEMP/EXPCUS AS
  SELECT CUSTNO, CUSTNAME, TURNOVER
    FROM PRODLIB/CUSTOMERS
   WHERE REGION = 'NORTH'
     AND TURNOVER > 0
CPYTOIMPF FROMFILE(QTEMP/EXPCUS)                    +
          TOSTMF('/home/export/customers-north.csv') +
          MBROPT(*REPLACE)                          +
          STMFCCSID(1208)                           +
          RCDDLM(*CRLF)                             +
          DTAFMT(*DLM)                              +
          STRDLM(*NONE)                             +
          FLDDLM(';')                               +
          ADDCOLNAM(*SQL)

With ADDCOLNAM(*SQL) the header comes from the view's column names, so renaming them in the SELECT (AS "Customer code") decides what the person opening the file reads, without touching the source file.

Note

STMFCCSID(1208) writes UTF-8 and is almost always the right choice. It is why accented letters come out correctly instead of as symbols: without it the file is written in the job's EBCDIC encoding, and whoever opens it on Windows sees the wrong characters.

Tip

where Excel is configured with the comma as the decimal separator (most of continental Europe) the right field delimiter is the semicolon, not the comma: with FLDDLM(',') numbers end up split across two columns.


Releases. CPYTOIMPF has been there forever. The ADDCOLNAM parameter, which writes column names as the first row, is more recent: if the command rejects it as an invalid keyword, the system is on a release that does not have it, and the header must be added separately.

← Back to blog

Comments

No comments yet. Be the first to comment!

You need an account to comment. Log in · Sign up