0

I need to convert my excel file (.xls) to tab delimited text file(.txt) in unix. Can anyone help me on this.

For eg. if i upload File.xls in server it should be converted as File.txt

Thanks for your replies.

1 Answers1

1

This should do what you want:

#!/usr/bin/perl -w

   use strict;
   use Spreadsheet::ParseExcel;

   my $parser   = Spreadsheet::ParseExcel->new();
   my $workbook = $parser->parse($ARGV[0]);

   if ( !defined $workbook ) {
      die $parser->error(), ".\n";
   }

   for my $worksheet ( $workbook->worksheets() ) {

      my ( $row_min, $row_max ) = $worksheet->row_range();
      my ( $col_min, $col_max ) = $worksheet->col_range();

      for my $row ( $row_min .. $row_max ) {
         my $line="";
         my $comma="";
         for my $col ( $col_min .. $col_max ) {

            my $cell = $worksheet->get_cell( $row, $col );
            next unless $cell;

            $line .= $comma;

            $line .= $cell->unformatted();
            # Could be $cell->unformatted() or $cell->value()
            $comma=",";
         }
         print $line,"\n";
      }
   }

Save the file as xls2csv then go to a terminal and make it executable with:

chmod +x xls2csv

Then you can run it with:

./xls2csv file.xls > file.csv

If you don't know how to install the spreadsheet module, you can do this:

sudo perl -MCPAN -e shell
cpan> install Spreadsheet::ParseExcel
cpan> q
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • Hi Mark, As i am new to unix i am trying to work it out.. but this dint work for me.. In what format i need to save the xls2csv file..and is it necessary to install spreadsheet module why because when i am executing the first line #sudo perl -MCPAN -e shell# i am getting an error like #user is not allowed to execute#.. pls help me out on this.. @Mark Setchell – Praveen kumar Aug 04 '14 at 07:02
  • Hi Praveen. You don't need to save the `xls2csv` file in any perticular format, it is just a text file that contains a script. But do not add a ".txt" extension to it - just save it with the name I said `xls2csv`. You can try `su` then enter root password, then do `perl -MCPAN -e shell`. – Mark Setchell Aug 04 '14 at 07:27