Linux에서 CSV를 XLS 파일로 변환

Linux에서 CSV를 XLS 파일로 변환

다음 Perl 스크립트는 CSV 파일을 XLS 파일로 변환할 수 있습니다.

문제는 클라이언트의 Linux 시스템에 많은 Perl 모듈을 설치해야 한다는 것입니다.

이 Perl 스크립트를 실행하려면 Linux 시스템이 게스트 시스템(모듈 설치를 허용하지 않음)이기 때문에 실제로 실행할 수 없습니다.

따라서 이 Perl 스크립트에 대한 다른 대안을 찾아야 합니다.

첫 번째 고객은 Linux Redhat 시스템 버전 5.X를 보유하고 있습니다.

좀 찾아보고 싶어배쉬/ksh/sh/awkPerl 스크립트와 동일한 작업을 수행하는 스크립트

그래서 CSV를 XLS 파일로 변환하는 다른 대안을 찾고 싶습니다.

이 스크립트를 어떻게 찾을 수 있나요? 또는 Linux 시스템에서 CSV를 XLS로 변환하기 위한 기타 제안

#!/usr/bin/perl -w

###############################################################################
#
# Example of how to use the WriteExcel module
#
# Simple program to convert a CSV comma-separated value file to an Excel file.
# This is more or less an non-op since Excel can read CSV files.
# The program uses Text::CSV_XS to parse the CSV.
#
# Usage: csv2xls.pl file.csv newfile.xls
#
#
# NOTE: This is only a simple conversion utility for illustrative purposes.
# For converting a CSV or Tab separated or any other type of delimited
# text file to Excel I recommend the more rigorous csv2xls program that is
# part of H.Merijn Brand's Text::CSV_XS module distro.
#
# See the examples/csv2xls link here:
#     L<http://search.cpan.org/~hmbrand/Text-CSV_XS/MANIFEST>
#
# reverse('©'), March 2001, John McNamara, [email protected]
#

use strict;
use Spreadsheet::WriteExcel;
use Text::CSV_XS;

# Check for valid number of arguments
if ( ( $#ARGV < 1 ) || ( $#ARGV > 2 ) ) {
    die("Usage: csv2xls csvfile.txt newfile.xls\n");
}

# Open the Comma Separated Variable file
open( CSVFILE, $ARGV[0] ) or die "$ARGV[0]: $!";

# 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;

# Row and column are zero indexed
my $row = 0;

while (<CSVFILE>) {
    if ( $csv->parse($_) ) {
        my @Fld = $csv->fields;

        my $col = 0;
        foreach my $token (@Fld) {
            $worksheet->write( $row, $col, $token );
            $col++;
        }
        $row++;
    } else {
        my $err = $csv->error_input;
        print "Text::CSV_XS parse() failed on argument: ", $err, "\n";
    }
}

답변1

CSV 파일을 XLS/XLSX 파일로 자동 변환하려면 다음을 사용할 수도 있습니다.SS 변환(Gnumeric에 포함) 또는우노프(리브레오피스 사용).

SSConvert 예

$ echo -e 'surname,name,age\nCarlo,Smith,23\nJohn,Doe,46\nJane,Doe,69\nSarah,Meyer,23\n' \
     > example.csv
$ unix2dos example.csv
$ ssconvert example.csv example.xlsx
$ ssconvert example.csv example.xls

첫 번째 ssconvert호출은 MS Excel 2007/2010 파일을 생성하고, 두 번째 호출은 레거시 Excel 2007 파일을 생성합니다.

다음을 통해 파일을 확인할 수 있습니다 file.

$ file example.csv
example.csv: ASCII text, with CRLF line terminators
$ file example.xls
example.xls: Composite Document File V2 Document, Little Endian, Os: Windows, Version 4.10,
   Code page: 1252, Create Time/Date: Tue Sep 30 20:23:18 2014
$ file example.xlsx 
example.xlsx: Microsoft Excel 2007+

다음을 통해 지원되는 모든 출력 파일 형식을 나열할 수 있습니다.

$ ssconvert --list-exporters
ID                           | Description
[..]
Gnumeric_Excel:xlsx2         | ISO/IEC 29500:2008 & ECMA 376 2nd edition (2008);
                               [MS Excel™ 2010]
Gnumeric_Excel:xlsx          | ECMA 376 1st edition (2006); [MS Excel™ 2007]
Gnumeric_Excel:excel_dsf     | MS Excel™ 97/2000/XP & 5.0/95
Gnumeric_Excel:excel_biff7   | MS Excel™ 5.0/95
Gnumeric_Excel:excel_biff8   | MS Excel™ 97/2000/XP
[..]

Unov 예

$ unoconv --format  xls example.csv

Excel 97/2000/XP 파일인 example.xls를 생성합니다.

파일을 통해 확인:

$ file example.xls 
example.xls: Composite Document File V2 Document, Little Endian, Os: Windows, Version 1.0,
  Code page: -535, Revision Number: 0

다음을 통해 지원되는 모든 파일 형식을 나열할 수 있습니다.

$ unoconv --show
[..]
The following list of spreadsheet formats are currently available:

  csv      - Text CSV [.csv]
  dbf      - dBASE [.dbf]
[..]
  ooxml    - Microsoft Excel 2003 XML [.xml]
[..]
  xls      - Microsoft Excel 97/2000/XP [.xls]
  xls5     - Microsoft Excel 5.0 [.xls]
  xls95    - Microsoft Excel 95 [.xls]
[..]

답변2

의 후속 버전 이자 더 작은 대안 인 ssconvertor 을 사용할 수 없습니다 . 마침내 나는 어떤 종속성도 없는 멋진 단일 바이너리를 발견했습니다.unoconvertunoconvlibreoffice --headlesscsv2xlsx.

복사해서 csv2xlsx_linux_amd64아래와 /usr/local/bin/csv2xlsx같이 사용했습니다.

csv2xlsx --columns="0:text,1:integer,2-3:text" --headerlines 1 --overwrite --colsep=";" --infile "$infile" --outfile "$outfile"

보시다시피 xslx 파일에서 사용할 열과 해당 셀의 형식을 정의하는 것도 가능합니다(이렇게 하면 Excel에서 언급된 "텍스트로서의 숫자" 경고를 피할 수 있습니다).지도 시간).

관련 정보