Neatly Printing A CSV File

October 4, 2019

Today’s exercise is another in my ongoing series of Awk programs that I write “under the radar” where I work. The complete program is on the next page, and has some localisms that you can ignore because won’t make sense. The key part of the program is this:

NR > 1 { nfields = csvsplit($0, csv); # print one record, with header/footer as needed
  if (pagelen - (linenum % pagelen) - lenfooter < lendetail) {
      while ((linenum + lenfooter) % pagelen != 0) { print ""; linenum++ }
      footer(); linenum += lenfooter }
  if (linenum % pagelen == 0) { pagenum++; header(); linenum += lenheader }
  detail(); linenum += lendetail
  if ((linenum + lenfooter) % pagelen == 0) { footer(); linenum += lenfooter } }

 

The pattern matches every record after the first line, which has the field names. The first if block makes sure there is enough space to print all the lines of a multi-line detail record on the current page; if not, it skips to the end of the page and writes the page footer. The second if advances the page and prints the page header when the record to be printed will be the first on the page. The detail() function actually prints the record. The third if prints the footer if the record wrote enough lines to reach the end of the page.

This program design requires the programmer to write a small Awk script that is combined with the base Awk script to produce a complete program. I’ve written CSV-to-text converters many times over the years, and always get stuck because the program has trouble figuring out column widths, or numeric formats, or multi-line records, or any of many other formatting needs. In this program, I punt to the user, giving him a complete description of the code he must provide, along with a sample so there is no confusion. I’m much happier with that approach than with all the other versions of this program that I have abandoned over the years.

You can see the program on the next page.

Advertisement

Pages: 1 2 3

3 Responses to “Neatly Printing A CSV File”

  1. John Cowan said

    To print a CSV file, fire up LibreOffice or Excel and tell it to print. Very simple.

    If you wanted a file instead, tell your program to print or export to a PDF file.

  2. […] the CSV file must be printed as well as loaded into Excel, and I wrote a program to do that in a previous exercise. I recently had a request to produce the output in HTML format, so I wrote that program […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: