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 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试