如何格式化excel文件的样式,字体,颜色,表格等与纯PHP


How to format excel file with styles, fonts, colors, tables etc with pure PHP?

我需要一种方法来写通过纯PHP格式的excel文件。警告:请注意,本Q不涉及库、插件等,请勿打扰。我在谷歌上搜索了很多,没有找到答案,但是在StackOverflow的一些文章中,有人提到了HTML/CSS格式的方法不工作的HTML格式解决方案我试过这样做,但在文件中保存的列中,填满了标签,什么也没发生。也许有一些专业人士可以帮助我用纯代码通过PHP, HTML, CSS或其他东西编写Excel。

再举一个例子,我已经用过这样的概念,但没有帮助:

    // headers for excel
$headers .= "<div style='font:bold 14px Times;'>Журнал остатков и инкассаций</div>'n";
$headers .= "Начало периода't ".date('d.m.Y')."0:00 'n";
$headers .= "Начало периода't ".date('d.m.Y')."23:59 'n'n";
$headers .= "Терминал't";
$headers .= "Место расположения't";
$headers .= "Дата't";
$headers .= "Время't";
$headers .= "Сумма инкассации't";
$headers .= "Банкноты't";
// excel content with overloaded terminals
if (mssql_num_rows($resCollection)>0) {
  while ($rowCollection = mssql_fetch_object($resCollection)) {
    $data .= $rowCollection->Name."'t".$rowCollection->Address."'t"
            .$rowCollection->TerminalNotes."'t".$rowCollection->TerminalAmount
            ."'t".$rowCollection->DayAmountAll."'t"
            .$rowCollection->LastPaymentTime."'n";
  }
}
$fileName = 'collection'.date('d_m_Y_H_i_s').'.xls';

header("Content-type: application/vnd.ms-excel");// application/excel had also been used
header("Content-Disposition: attachment; filename=$fileName");
echo iconv('utf-8', 'cp1251', "$headers'n$data"); 

我不仅用过div和tables,但它们都不起作用

下面的例子可能会对您有所帮助:

  1 <?php
  2 header('Content-type: application/excel');                                  
  3 header('Content-Disposition: attachment; filename="test.xls"');
  4 ?>
  5 
  6 <table>
  7 <tr><th>Column 1</th><th>Column 2</th></tr>
  8 <tr><td style="font-size:200%">Answer 1</td><td style="color:#f00">Answer 2<    /td></tr>
  9 <tr><td colspan="2" style="font-weight:bold">Answer 3 with 2 columns</td></t    r>
 10 </table>

在服务器上保存为.php文件

它的作用是:添加标题来强制浏览器发送Excel文件。然后返回其中的一个表。我的Excel能很好地处理这些。

注意:示例HTML来自您已经找到的答案。我只是在开头添加了标题。

注意:你只是改变了你的问题,增加了一个例子。你的例子没有使用html!您正在交付一个以制表符分隔的文件,其中每行以换行符结束。

正确的方法是真正生成HTML,即,在开始使用<table>,每行使用<tr></tr>,并将字段放在<td>标记中,然后以关闭</table>结束,所以基本上:

$data='<table>';
// excel content with overloaded terminals
if (mssql_num_rows($resCollection)>0) {
  while ($rowCollection = mssql_fetch_object($resCollection)) {
    $data.='<tr>';
    $data .= '<td>'.$rowCollection->Name."</td><td>".$rowCollection->Address."</td><td>"
            .$rowCollection->TerminalNotes."</td><td>".$rowCollection->TerminalAmount
            ."</td><td>".$rowCollection->DayAmountAll."</td><td>"
            .$rowCollection->LastPaymentTime."</td>";
    $data.='</tr>';
  }
}
$data.='</table>';

然后将最后一行改为:

echo iconv('utf-8', 'cp1251', "$data"); 

如果工作,我建议你改变输出有<th>标签周围的表标题,而不是在你的例子中的div。