doutou1922 2015-10-10 12:53
浏览 92
已采纳

将数组数据转换为Excel

I am converting array data into Excel using PHPExcel. When Excel file is created, data is stored row wise but I want to store data column wise. My array is given below:

array (size=3)
  0 => string '8801755568952' (length=13)
  1 => string '8801755556987' (length=13)
  2 => string '8801755587985' (length=13)

My array to Excel conversion code is:

$objPHPExcel->getActiveSheet()->fromArray($csv_data, null, 'A1')  
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    return $objWriter->save($xls_output_path);

My output is:

8801755568952 8801755556987 8801755587985

My desired output is:

8801755568952 
8801755556987 
8801755587985
  • 写回答

1条回答 默认 最新

  • dongyi9783 2015-10-10 13:02
    关注

    If you pass a simple 1-dimensional array to the fromArray() method, then PHPExcel assumes that it is a single row, which is what you're seeing.

    Either convert your array to a 2-dimensional array

    As PHPExcel will treat these values as numeric, and they're larger than the limit for a 32-bit signed integer in PHP (and you're probably running 32-bit PHP), they'll be cast to float, and you'll potentially lose accuracy, so I wouldn't use this approach myself.

    If you do want to convert the array to a 2-dimensional array, then use:

    $csv_data = call_user_func_array(
        'array_map',
        array_merge(array(NULL), [$csv_data])
    );
    

    Or just loop over it writing to each row individually

    $row = 1;
    foreach($csv_data as $cellData) {
        $objPHPExcel->getActiveSheet()->setCellValueExplicit('A'.$row++, $cellData);
    }
    

    The use of setCellValueExplicit() will force the values to be treated as a string, so nothing will be cast to float, so no loss of precision

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集