mysql和php到excel

06odsfpq  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(322)

我的mysql表中有人力资源应用程序,我正在尝试将这些数据下载为excel文件。

function exportExcel($filename='ExportExcel',$columns=array(),$data=array(),$replaceDotCol=array()){
   global $connect;
    header('Content-Encoding: UTF-8');
    header('Content-Type: text/plain; charset=utf-8'); 
    header("Content-disposition: attachment; filename=".$filename.".xls");
    echo "\xEF\xBB\xBF"; // UTF-8 BOM
    $count=count($columns);
    echo '<table border="1">';
    echo '<th>1</th>';
    echo '<th>2</th>';
    foreach($columns as $col){
        echo '<tr><th>'.trim($col).'</th>';
        foreach($data as $val){
            for($i=0; $i < $count; $i++){
                if(in_array($i,$replaceDotCol)){
                    echo '<td>'.str_replace('.',',',$val[$i]).'</td></tr>';
                }else{
                    echo '<td>'.$val[$i].'</td></tr>';
                }
            }
        }
    }
}

我向函数发送了两个数组,其中一个包含诸如姓名、生日、出生地等描述,另一个是我的mysql数据。
我的目标是,在两列中显示这些信息。在我的代码中,输出显示只喜欢行。

72qzrwbm

72qzrwbm1#

除了html结构,我的foreach循环也有错误。看来我不需要它们。简单地说,对所有数组使用一个while循环可以提供正确的显示。我是新手。

function exportExcel($filename='ExportExcel',$columns=array(),$data=array(),$replaceDotCol=array()){
   global $connect;
    header('Content-Encoding: UTF-8');
    header('Content-Type: text/plain; charset=utf-8'); 
    header("Content-disposition: attachment; filename=".$filename.".xls");
    echo "\xEF\xBB\xBF"; // UTF-8 BOM

    $count=count($columns);
    $i = 0  ;
    echo '<table border="1">';
    while ($i<=$count) {
        echo "<tr>";
        echo "<th>" .$columns[$i]."</th>";
        echo "<td style='width='60%''>" .$data[$i]. "</td>";
        echo "<tr>";
        $i++;

    }
    echo "</table>";

}

显示

zc0qhyus

zc0qhyus2#

您正在使用关闭行 </tr> 每次写入列值时。所以a)你的最终标记可能是无效的(尽管excel可能会容忍它并猜测你的意思)和b)这就是为什么所有东西都在一列中。只关闭 <tr> 当您将所有想要的列写入该行时。另外,您没有正确输出标题行,它正在合并到数据中。
这应该起作用:

echo '<tr>'; //header row

foreach($columns as $col){
    echo '<th>'.trim($col).'</th>';
}

echo '</tr>'; //end header row

foreach($data as $val){
    echo '<tr>'; //begin data row
    for($i=0; $i < $count; $i++){
        if(in_array($i,$replaceDotCol)){
            echo '<td>'.str_replace('.',',',$val[$i]).'</td>';
        }else{
            echo '<td>'.$val[$i].'</td>';
        }
    }
    echo '</tr>'; //end data row
}

相关问题