PHPexcel - 如何从url加载excel文件

时间:2013-01-29 08:43:47

标签: phpexcel

我正在使用以下代码来加载,读取,写入和下载excel文件。

//include PHPExcel library

require_once "Classes/PHPExcel/IOFactory.php";

//load Excel template file

$objTpl = PHPExcel_IOFactory::load("excel.xls");
$objTpl->setActiveSheetIndex(0);  //set first sheet as active

$objTpl->getActiveSheet()->setCellValue('C2', date('Y-m-d'));  //set C1 to current date

$objTpl->getActiveSheet()->getStyle('C2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); //C1 is right-justified

$strData = $objTpl->getActiveSheet()->getCell('C3')->getValue();
$strData .= $objTpl->getActiveSheet()->getCell('C4')->getValue();

$objTpl->getActiveSheet()->setCellValue('C3', 'It\'s working');
$objTpl->getActiveSheet()->setCellValue('C4', 'Dynamic excel read and writing');
$objTpl->getActiveSheet()->setCellValue('C6', 'Data read: C3 = '.substr($strData,0,1).' and C4 = '.substr($strData,1,1));

$objTpl->getActiveSheet()->getStyle('C4')->getAlignment()->setWrapText(true);  //set wrapped for some long text message

$objTpl->getActiveSheet()->getColumnDimension('C')->setWidth(40);  //set column C width

$objTpl->getActiveSheet()->getRowDimension('4')->setRowHeight(120);  //set row 4 height

$objTpl->getActiveSheet()->getStyle('A4:C4')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP); //A4 until C4 is vertically top-aligned

//prepare download

$filename=mt_rand(1,100000).'.xls'; //just some random filename

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');

$objWriter = PHPExcel_IOFactory::createWriter($objTpl, 'Excel5');  //downloadable file is in Excel 2003 format (.xls)

$objWriter->save('php://output');  //send it to user, of course you can save it to disk also!

我的问题是我想从不同的源(url,stream)加载excel文件,而不是从本地目录加载

1 个答案:

答案 0 :(得分:0)

只需将文件保存到您的服务器,然后阅读即可。

    file_put_contents('excel.xls',  
          file_get_contents('https://www.myweburl.com/spreadsheets.xls')
        );

    $objTpl = PHPExcel_IOFactory::load("excel.xls");