Update: I missed the Excel/Access requirement, but I can't test that, so I don't even know if this will work or not. It's meant for CSV./Update

Here's a quick attempt that isn't really efficient (it has to read the file twice, first to get the max widths, then to write it out), but it does do what you want (from what I can tell). It puts your first requirement (the padded entries) into a file called out.1, and the output for your second requirement in out.2.

use warnings; use strict; use Text::CSV; my $csv = Text::CSV->new; my $file = 'in.csv'; my $out1 = 'out.1'; my $out2 = 'out.2'; open my $fh, '<', $file or die "can't open the damned csv file!: $!"; my %widths; while (my $row = $csv->getline($fh)){ for (0..$#$row){ my $length = length $row->[$_]; if (! $widths{$_} || $length > $widths{$_}){ $widths{$_} = $length; } } } seek $fh, 0, 0; open my $wfh_1, '>', $out1 or die "can't open the bloody output file $out1!: $!"; open my $wfh_2, '>', $out2 or die "can't open the dirty output file $out2!: $!"; my @header; my $got_header; while (my $row = $csv->getline($fh)){ @header = @$row if ! $got_header; $got_header = 1; for (0..$#$row){ if (@header){ print $wfh_2 "$header[$_] : $row->[$_]\n"; } my $elem_len = $widths{$_} - length($row->[$_]); $row->[$_] .= ' ' x $elem_len; } print $wfh_1 join(' ', @$row); print $wfh_1 "\n"; } close $fh; close $out1; close $out2;

-stevieb


In reply to Re: converting a csv file to fix width text by stevieb
in thread converting a csv file to fix width text by jazzlover

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.