利用PHPExcel实现数据保存到excel文件 php excel 设置单元格格式为文本格式

时间:2024-03-10 14:15:37
    include(dirname(__FILE__) .\'/phpexcel-1.7.7/Classes/PHPExcel.php\');
    include(dirname(__FILE__) .\'/phpexcel-1.7.7/Classes/PHPExcel/IOFactory.php\');


    $header_arr = array(\'A\',\'B\',\'C\',\'D\',\'E\',\'F\',\'G\',\'H\',\'I\',\'J\',\'K\',\'L\',\'M\', \'N\',\'O\',\'P\',\'Q\',\'R\',\'S\',\'T\',\'U\',\'V\',\'W\',\'X\',\'Y\',\'Z\');
    $objPHPExcel = new PHPExcel();//实例化一个要保存的phpExcel对象

//写数据开始

    //在激活的工作区写入数据 (单条写入数据演示)
    $objPHPExcel->getActiveSheet()->setCellValue(\'B8\', \'汉字\');

    //在激活的工作区写入数据 (数组写入数据演示)
    $startRow = 1;
    foreach ($list as $row) {
        foreach ($indexKey as $key => $value){
            //这里是设置单元格的内容
            $objActSheet->setCellValue($header_arr[$key].$startRow,$row[$value]);
        }
        $startRow++;
    }


//写数据结束

    $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
    $objWriter->save($file);

 

1、设置单元格为文本

//设置A3单元格为文本
$objPHPExcel->getActiveSheet()->getStyle(\'A3\')->getNumberFormat()
    ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
//也可以设置整行或整列的style
/*
//E 列为文本
$objPHPExcel->getActiveSheet()->getStyle(\'E\')->getNumberFormat()
    ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
//第三行为文本
$objPHPExcel->getActiveSheet()->getStyle(\'3\')->getNumberFormat()
    ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
*/

2、在设置值的时候显示的指定数据类型

$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle(\'Simple\');

$objPHPExcel->getActiveSheet()->setCellValueExplicit(\'D1\',123456789033,PHPExcel_Cell_DataType::TYPE_STRING);

3、在数字字符串前加一个空格使之成为字符串

$objPHPExcel = new PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setTitle(\'Simple\');

$objPHPExcel->getActiveSheet()->setCellValue(\'D1\', \' \' . 123456789033);

 

单元格宽度设置和自适应

//设置宽度      
$objPHPExcel->$objActSheet->getColumnDimension(\'B\')->setAutoSize(true);      
$objPHPExcel->$objActSheet->getColumnDimension(\'A\')->setWidth(30);

 

 设置默认高度

//设置默认行高
$objPHPExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(30);

 

 

 

 

 

参考: https://blog.csdn.net/weixin_39696369/article/details/78646494

 

参考: http://www.netingcn.com/phpexcel-big-number-display.html