3

下面的代码有效,但在 Excel 中打开时,所有数据都显示在一行(但不同的列)中。查询应该显示数据标题,第 1 行和第 2 行。此外,当我打开文件时,我收到一条警告,上面写着“您尝试打开的文件,'xxxx.csv',格式不同于“ 无论如何要解决这个问题?这也可能是原因。

tldr; 导出到具有多行的 csv - 而不仅仅是一行。修复 Excel 错误。谢谢!

#!/usr/bin/perl
use warnings;
use DBI;
use Text::CSV;


# local time variables
($sec,$min,$hr,$mday,$mon,$year) = localtime(time);
$mon++;
$year += 1900;

# set name of database to connect to
$database=MDLSDB1;

# connection to the database
my $dbh = DBI->connect("dbi:Oracle:$database", "", "")
or die "Can't make database connect: $DBI::errstr\n";

# some settings that you usually want for oracle 10 
$dbh->{LongReadLen} = 65535; 
$dbh->{PrintError} = 0;  

# sql statement to run
$sql="select * from eg.well where rownum < 3";

my $sth = $dbh->prepare($sql);
$sth->execute();


my $csv = Text::CSV->new ( { binary => 1 } )             
or die "Cannot use CSV: ".Text::CSV->error_diag (); 

open my $fh, ">:raw", "results-$year-$mon-$mday-$hr.$min.$sec.csv"; 

$csv->print($fh, $sth->{NAME});

while(my $row = $sth->fetchrow_arrayref){      

$csv->print($fh, $row);
}

close $fh or die "Failed to write CSV: $!"; 
4

2 回答 2

11
while(my $row = $sth->fetchrow_arrayref){   
  $csv->print($fh, $row);
  $csv->print($fh, "\n");
}

CSV rows are delimited by newlines. Just simply add a newline after each row.

于 2012-06-01T20:38:27.580 回答
2

我认为另一种解决方案是使用Text::CSV对象的实例化并在那里传递所需的线路终止...

my $csv = Text::CSV->new ( { binary => 1 } )             
  or die "Cannot use CSV: " . Text::CSV->error_diag();

变成:

my $csv = Text::CSV->new({ binary => 1, eol => "\r\n" })
  or die "Cannot use CSV: " . Text::CSV->error_diag();
于 2014-03-06T16:35:01.073 回答