我想问你的帮忙。PHP Excel和Codeigniter
我在做一个使用CodeIgniter的项目,除了我制作的图表外,我还需要生成Excel文件。我正在使用PHPExcel来生成Excel文件。
我在项目的third_party文件夹中添加了Classes文件夹。
我创建了一个名为Excel.php项目的库文件夹与文件的代码:
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
require_once APPPATH."/third_party/Classes/PHPExcel.php";
class Excel extends PHPExcel {
public function __construct() {
parent::__construct();
}
}
我认为文件中,我使用AJAX来发送数据并进行处理的控制器,该控制器我在那里放置了PHPExcel的代码。下面是我在视图代码:
$("#excel").click(function(){
var fromDate = $("#fromDate").val();
var toDate = $("#toDate").val();
var dataString = "fromDate="+fromDate+"&toDate="+toDate;
$.ajax({
//url of the function
url: '<?php echo base_url(); ?>index.php/charts/excel',
//set type post
type: 'POST',
//get the data from the input field
data: dataString,
success:function(data)
{
alert(data);
}
});
});
这是我在控制器代码:
public function excel()
{
$this->load->library('Excel');
//activate worksheet number 1
$this->excel->setActiveSheetIndex(0);
//name the worksheet
$this->excel->getActiveSheet()->setTitle('Users list');
$sDate = $this->input->post('fromDate');//date_create_from_format('Y-m-d', $_POST['fromDate']);
$eDate = $this->input->post('toDate');//date_create_from_format('Y-m-d', $_POST['toDate']);
$data = $this->Charts_model->hello($sDate,$eDate);
// read data to active sheet
//print_r($data);
$row = 1;
foreach($data as $r){
$this->excel->getActiveSheet()->fromArray(array($r->emp_id, $r->emp_stat, $r->isActive, $r->dateStarted), null, 'A'.$row);
$row++;
}
$filename='just_some_random_name.xls'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
//if you want to save it as .XLSX Excel 2007 format
$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
//force user to download the Excel file without writing it to server's HD
$objWriter->save('php://output');
}
控制器似乎是工作,但是,它不下载任何Excel文件。
因此,我试着提醒控制器返回的数据,并且this是提醒时的外观。
我希望你能帮我解决这个问题。由于
UPDATE
的问题就解决了。事实证明,它已经在下载文件。当我检查目录时,文件存在。
我所做的是我添加了一个锚点标记,如果导出成功,它会触发该文件实际下载并在页面下方看到。
$("#someid").trigger("click").attr("target", "_blank");
锚标记看起来是这样的:
<a href="<?php echo base_url(); ?>/directoryofthefile/somename.xls" style="display: none;">
<input type="button" id="someid" value="Test" class="btn btn-success">
</a>
未来,使用'console.log()'而不是'alert()'进行调试。这是一个更好的习惯,是互动的。 – Goose