将XML数据转换为Excel

时间:2014-05-08 14:11:09

标签: php xml excel

您将如何将具有以下结构的XML数据转换为带有格式化单元格的Excel文件(标题的粗体字体),以及在转换后的电子表格末尾汇总 hours_total 的函数,并自动过滤应用于标题?

我使用SimpleXML将XML加载到PHP脚本中,如下所示:

PHP

$sxml = simplexml_load_file($url);
return $sxml;

然后遍历每一行,只选择我需要转换为Excel的内容,如 CaseNbr 摘要 Hours_total 。休息被忽略了。

XML

<results>
    <row Result_Number="1">
        <CaseNbr>4845</CaseNbr>
        <Urgency>High</Urgency>
        <hours_total>3.75</hours_total>
        <status>RESOLVED</status>
        <date_resolved>1/6/2014 1:01:36 PM</date_resolved>
        <customer_name>A Big Guy</customer_name>
        <contact>Bane</contact>
        <Address_Line1>...</Address_Line1>
        <Address_Line2>...</Address_Line2>
        <City>...</City>
        <State>...</State>
        <Summary>...</Summary>
    </row>
    <row Result_Number="2">
        ...
    </row>
</results>

修改

function generateReport($sxml){
            // generate the report if XML data was successfully extracted
            if(isset($sxml)){
                $html = null;
                $html .= '<p>Customer: ' . $_GET['customer'] . '</p>';
                $html .= '<p>Period: ' . date('F j, Y', strtotime($_GET['from'])) . ' - ' . date('F j, Y', strtotime($_GET['to'])) . '</p>';
                $total_actual_hours = 0;
                $html .= '<table cellspacing="0" cellpadding="2" style="border: 1px solid black;">';
                foreach($sxml->row as $row){
                    $html .=    // for the sake of simplicity I will explain what happens here
                                // I echo <tr>'s, <td>'s and actual data I want like so:
                                // $row->Summary, and I also sanitize it
                    $total_actual_hours += (float)$row->hours_total; // this is the total hours of all CaseNbrs
                }
                $html .= '<tr style="background-color:#C0C0C0;font-weight:bold;font-size:1.15em;">';
                $html .= '<td>Total(hrs): </td>';
                $html .= '<td colspan="3" style="text-align:right;vertical-align:top;">' . $total_actual_hours . '</td>';
                $html .= '</tr>';
                $html .= '</table>';
                echo $html;
            }
        }

然后我创建了一个链接,使用Javascript:

将回显的HTML表下载为XLS
<script type='text/javascript'>//<![CDATA[ 
    window.onload=function(){
      makeTextFile = function (text) {
        var data = new Blob([text], {type: 'text/plain'});
        textFile = window.URL.createObjectURL(data);
        return textFile;
      };

    document.getElementById('downloadxls').href = makeTextFile(document.getElementsByTagName('html')[0].outerHTML);
    }//]]>  

</script>

0 个答案:

没有答案