I know you "found" the code on the internetz and did not write it yourself. Maybe it is time to find better example sites than, as this is bad code: do not mix diamond read with parse on CVS, as it will break on embedded line separators.

Of course I have no idea what version of Text::CSV_XS you are using, but this should be simplified to something like:

use strict; use warnings; # <-- always use strict *and* warnings use Spreadsheet::WriteExcel; use Text::CSV_XS; # Check for valid number of arguments <-- @ARGV in scalar context give +s the number of entries in the list @ARGV == 2 or die "Usage: csv2xls csvfile.txt newfile.xls\n"; # Open the Comma Separated Variable file open my $fh, "<", $ARGV[0] or die "$ARGV[0]: $!"; # <-- use lexical fi +le handles and 3-arg open # Create a new Excel workbook my $workbook = Spreadsheet::WriteExcel->new ($ARGV[1]); my $worksheet = $workbook->add_worksheet (); # Create a new CSV parsing object my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 }); # <--- +use diagnostics and binary # Row and column are zero indexed my $row = 0; while (my $row = $csv->getline ($fh)) { # <-- safe and fast parsing # due to auto_diag there is no reason for error-checking my $col = 0; $worksheet->write ($row, $col++, $_) for @{$r}; $row++; }

Now, doesn't that read much easier? Also easier to extend and to maintain.

Note that this is a basic simplified example from your code. The tools mentioned by the others also take note of dates and special formats if you want and have examples of how to deal with errors. (and csv2xlsx can merge many CSV files into a single Excel file.


Enjoy, Have FUN! H.Merijn

In reply to Re: convert csv with quotes to xls by Tux
in thread convert csv with quotes to xls by Anonymous Monk

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.