我正在處理一個需要從 Web URL 訪問 CSV 檔案的專案。我可以在終端中訪問該檔案并列印來自 CSV 檔案的內容,但我無法生成 HTML 表格(然后我將使用 MIME 發送電子郵件)。
這是我的代碼 - 我需要將完整的 CSV 檔案作為 HTML 表格發送到我的電子郵件。
#!/usr/bin/perl
use strict;
use warnings;
use LWP::Simple;
use POSIX qw(strftime);
use MIME::Lite;
use Getopt::Long;
my $to="pankajdustbin\@gmail.com";
my $from="pankajdustbin\@gmail.com";
$subject="CSV File";
my $content = `curl -s "https:csvfile.com"`;
@output = split(/\n/,$content);
foreach my $line (@output) {
my ($col1, $col2, $col3, $col4, $col5, $col6) = split(/,/, $line);
#print "\n$col1, $col2, $col3, $col4, $col5, $col6\n";
$message = "<tr> <td>$col1</td> <td>$col2</td> <td>$col3</td> <td>$col4</td> <td>$col5</td> <td>$col6</td></tr>";
}
my $msg=MIME::Lite->new(
From => $from,
To => $to,
Subject => $subject,
Data => $message
);
$msg->attr('content-type' => 'text/html');
#MIME::Lite->send("smtp");
$msg->send;
使用此代碼,HTML 表僅包含 CSV 的最后一行。有人可以幫我怎么辦嗎?
CSV 有大約 100 行,我在終端中看到的示例輸出如下:
1.2.3.4 03-04-2022. 03-08-2022. Red. 1%. Positive
5.2.3.4 03-05-2022. 04-08-2022. Blue. 1%. Neutral
and so on...
uj5u.com熱心網友回復:
問題是您$message每次通過foreach回圈都會覆寫變數的內容。這意味著$message它將只有您分配給它的最后一個值。
您可以使用運算子附加到變數的內容.=:
my $message;
foreach my $line (@output) {
my ($col1, $col2, $col3, $col4, $col5, $col6) = split(/,/, $line);
$message .= "<tr> <td>$col1</td> <td>$col2</td> <td>$col3</td> <td>$col4</td> <td>$col5</td> <td>$col6</td></tr>";
}
uj5u.com熱心網友回復:
先前的答案涵蓋了您在回圈中覆寫了您$message不想要的內容。
以下代碼段演示了使用拆分和for回圈構建 html表的略有不同的方法。
然后可以隨心所欲地使用表格——通過郵件發送或生成html頁面。在此演示代碼中生成了完整的html頁面。
注意#1:可選,\n僅用于html可讀性\t
注意#2:由于沒有提供示例輸入CVS檔案,因此假定內容基于終端中提供的輸出
use strict;
use warnings;
use feature 'say';
my $table = '<table border=1>';
while( my $line = <DATA>) {
chomp $line;
$table .= "\n\t\t\t<tr>";
$table .= "\n\t\t\t\t<td>" . $_ . '</td>' for split(/,/,$line);
$table .= "\n\t\t\t</tr>";
}
$table .= "\n\t\t</table>";
my $html =
"<html lang='en'>
<head>
<meta charset='utf8' />
<link rel='stylesheet' href='css/styles.css'>
<title>
CVS table
</title>
</head>
<body>
$table
</body>
</html>
";
say $html;
__DATA__
1.2.3.4,03-04-2022,03-08-2022,Red,1%,Positive
5.2.3.4,03-05-2022,04-08-2022,Blue,1%,Neutral
1.2.3.4,03-04-2022,03-08-2022,Red,1%,Positive
5.2.3.4,03-05-2022,04-08-2022,Blue,1%,Neutral
1.2.3.4,03-04-2022,03-08-2022,Red,1%,Positive
5.2.3.4,03-05-2022,04-08-2022,Blue,1%,Neutral
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495704.html
