`
ljqian
  • 浏览: 6790 次
  • 性别: Icon_minigender_1
  • 来自: 常熟
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
php导入导出excel方法 excel, php
<?php
//导出excel
/**
     * @param string $filname             //输出的文件名
     * @param string $type                //编码类型
     * @param string $array              //excel的标题
     * @param string $data               //需要的数据data
     * eg.exportExcel(test, 'utf-8', array('测试','OK'),array(array('ceshishuju1','OK1'),array('ceshi2','OK2'),array('ceshi3',''),array('','OK4')));
     **/
    function exportExcel($filname, $type = 'utf-8', $array, $data) {
        if (empty ($data)) {
            echo "<script>alert('sorry,no data!');history.go(-1);</script>";
            exit;
        }
        $filname = iconv("utf-8", "gb2312", $filname);
        header("Content-type:application/vnd.ms-excel;");
        header("Content-Disposition:attachment;filename=$filname.xls");
        echo "<META HTTP-EQUIV='Content-Type' CONTENT='text/html;charset=$type'>";
        echo '<table border="1" cellspacing="1" cellpadding="1"><tr align="center">';
        foreach ($array as $val) {
            echo "<td width='100'>$val</td>";
        }
        echo '</tr>';
        foreach ($data as $val) {
            if(is_array($val)){
                echo '<tr align="center">';
                foreach ($val as $v) {
                echo '<td width="120" height="30">' . $v . '</td>';
                }
                echo '</td>';
            }else {
                echo '<tr align="center">';
                echo '<td width="120" height="30">' . $val . '</td>';
                echo '</td>';
            }
        }
        echo '</table>';
        exit;
    }
?>

<?php  
//导入excel

    $excelfile = $_FILES['excelfile'];  
    $filename = $excelfile['name'];  
    $tmp_name = $excelfile['tmp_name'];  
    move_uploaded_file ($tmp_name,'/upload/'.$filename);  
//reader.php需要从 http://sourceforge.net/projects/phpexcelreader 下载
//reader.php中的require_once 'Spreadsheet/Excel/Reader/OLERead.php';这行代码需要进行修改
//修改为引用与它同文件下的oleread.inc      
    require_once ('reader.php');  
    $data = new Spreadsheet_Excel_Reader();  
    $data->setOutputEncoding('gbk');  
    $data->read('/upload/'.$filename);  
    $customs = array();  
// $data->sheets[0]['numRows']为Excel行数    
// $data->sheets[0]['numCols'] 为Excel列数  
    for($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {//$i为2是由于第一行为各字段的标题  
        $id = mysql_real_escape_string($data->sheets[0]['cells'][$i][1]);  
        $title = mysql_real_escape_string($data->sheets[0]['cells'][$i][2]);  
        $tel = mysql_real_escape_string($data->sheets[0]['cells'][$i][3]);  
        $description = mysql_real_escape_string($data->sheets[0]['cells'][$i][4]);  
        array_push($customs, array('title'=>$title,'tel'=>$tel,'description'=>$description));  
    }  
        var_dump($customs);  
//打印出的数据格式是excel中每行内容组成的数组,在上述的代码中只打印1-4列的内容  
?> 
Global site tag (gtag.js) - Google Analytics