Commit 88b66715 by Phạm Văn Đoan

code chức năng xuất báo cáo ra excel của tuần và tháng

parent ab73e782
......@@ -6,7 +6,10 @@
* Time: 2:22 CH
*/
if (!defined('BASEPATH')) exit('No direct script access allowed');
require_once APPPATH."/third_party/PHPExcel.php";
//require_once APPPATH."/third_party/PHPExcel.php";
//include FCPATH . "/application/third_party/PHPExcel/IOFactory.php";
include FCPATH . "/application/third_party/PHPExcel.php";
class CmsRanking extends CI_Controller
{
public function __construct()
......@@ -15,6 +18,7 @@ class CmsRanking extends CI_Controller
date_default_timezone_set("Asia/Ho_Chi_Minh");
//
$this->load->model('track_model');
$this->load->model('user_model');
$this->load->model('report_views_daily_model');
$this->load->model('report_views_weekly_model');
$this->load->model('report_views_monthly_model');
......@@ -109,57 +113,165 @@ class CmsRanking extends CI_Controller
$this->load->view('backend/ajax/cms_ranking/list_by_monthly_view', $data);
}
public function exportExcel() {
$data = array();
$fByName = $this->input->post('fByName');
//
print_r($fByName);
$limit = 100;
$data = $this->report_views_monthly_model->cmsGetPagination($limit, '', $fByName);
//Khởi tạo đối tượng
$excel = new PHPExcel();
//Chọn trang cần ghi (là số từ 0->n)
$excel->setActiveSheetIndex(0);
//Tạo tiêu đề cho trang. (có thể không cần)
$excel->getActiveSheet()->setTitle('demo ghi dữ liệu');
//Xét chiều rộng cho từng, nếu muốn set height thì dùng setRowHeight()
$excel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
$excel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
//Xét in đậm cho khoảng cột
$excel->getActiveSheet()->getStyle('A1:C1')->getFont()->setBold(true);
//Tạo tiêu đề cho từng cột
//Vị trí có dạng như sau:
/**
* |A1|B1|C1|..|n1|
* |A2|B2|C2|..|n1|
* |..|..|..|..|..|
* |An|Bn|Cn|..|nn|
*/
$excel->getActiveSheet()->setCellValue('A1', 'Tên Bài Hát');
$excel->getActiveSheet()->setCellValue('B1', 'Ca Sĩ');
$excel->getActiveSheet()->setCellValue('C1', 'Tổng điểm');
// thực hiện thêm dữ liệu vào từng ô bằng vòng lặp
// dòng bắt đầu = 2
$numRow = 2;
foreach ($data as $row) {
$excel->getActiveSheet()->setCellValue('A' . $numRow, $row['name_song']);
$excel->getActiveSheet()->setCellValue('B' . $numRow, $row['all_name']);
$excel->getActiveSheet()->setCellValue('C' . $numRow, $row['total_point']);
$numRow++;
public function exportReport($type, $time)
{
if ($type && $time) {
$arrayTime = explode('-', $time);
$week = date('W');
$month = date('n');
$year = date('Y');
if ($type == 'week') {
$week = trim($arrayTime[0]);
$year = trim($arrayTime[1]);
$filename = 'Weekly-tuan' . (($week < 10) ? '0'.$time : $time);
$reports = $this->track_model->getReportWeekly($week, $year);
} elseif ($type == 'month') {
$month = trim($arrayTime[0]);
$year = trim($arrayTime[1]);
$filename = 'Monthly-' . (($month < 10) ? '0'.$time : $time);
$reports = $this->track_model->getReportMonthly($month, $year);
}
$count_views = [];
foreach ($reports as $key => $result) {
$list_user = $this->track_model->getUserByTrack($result['track_id']);
$casi[$key] = [];
if ($list_user && count($list_user) > 0) {
foreach ($list_user as $k => $users){
$singer = $this->user_model->getUser($users['user_id']);
if ($singer) {
$casi[$key][] = $singer[0]['full_name'];
}else {
$casi[$key][] = $list_user[$k]['name'];
}
}
}
$list_artists = $this->track_model->getArtistsByTrack($result['track_id']);
$nhacsi[$key] = [];
if ($list_artists ) {
foreach ($list_artists as $k_art => $art){
$artist = $this->user_model->getUser($art['user_id']);
if ($artist) {
$nhacsi[$key][] = $artist[0]['full_name'];
}else {
$nhacsi[$key][] = $list_artists[$k_art]['name'];
}
}
}
$track_detail = $this->track_model->getTrackById($result['track_id']);
$track_detail = $track_detail[0];
$count_views[] = array(
'A' => $result['order'],
//'B' => ($track_detail['title'] != '') ? $track_detail['title'] . ' (' . $track_detail['id'] . ')' : '',
'B' => ($track_detail['title'] != '') ? $track_detail['title'] : '',
'C' => ($casi[$key] && count($casi[$key]) > 0 ) ? implode(", ", $casi[$key]) : '',
'D' => ($nhacsi[$key] && count($nhacsi[$key]) > 0 ) ? implode(", ", $nhacsi[$key]) : '',
'E' => number_format($result['views_zing']),
'F' => number_format($result['views_nct']),
'G' => number_format($result['views_keeng']),
'H' => 0,
'I' => number_format($result['point_zing']),
'J' => number_format($result['point_nct']),
'K' => number_format($result['point_keeng']),
'L' => 0,
'M' => number_format($result['total_point'])
);
}
$objPHPExcel = new PHPExcel;
// set default font
$objPHPExcel->getDefaultStyle()->getFont()->setName('Tahoma');
// set default font size
$objPHPExcel->getDefaultStyle()->getFont()->setSize(10);
// writer already created the first sheet for us, let's get it
$objSheet = $objPHPExcel->getActiveSheet();
// rename the sheet
$objSheet->setTitle($filename);
$objSheet->getCell('A1')->setValue("Rank");
$objSheet->getCell('B1')->setValue("Song Title");
$objSheet->getCell('C1')->setValue("Artist");
$objSheet->getCell('D1')->setValue("Composer");
$objSheet->getCell('E1')->setValue("Zing Stream");
$objSheet->getCell('F1')->setValue("NCT Stream");
$objSheet->getCell('G1')->setValue("Keeng Stream");
$objSheet->getCell('H1')->setValue("Nhac.vn Stream");
$objSheet->getCell('I1')->setValue("Zing Point");
$objSheet->getCell('J1')->setValue("NCT Point");
$objSheet->getCell('K1')->setValue("Keeng Point");
$objSheet->getCell('L1')->setValue("Nhac.vn Point");
$objSheet->getCell('M1')->setValue("TOTAL POINT");
$border_style = array(
'borders' =>array(
'allborders' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN,
'color' => array('rgb' => '000000')
)
)
);
$style_header = array(
'font' => array(
'bold' => true,
),
'alignment' =>array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
'vertical' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
),
'fill' =>array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => '8DB4E2'),
),
);
$objSheet->getStyle('A1:M1')->applyFromArray($style_header);
$objSheet->getStyle("A1:M1")->applyFromArray($border_style);
$style_top10 = array(
'font' => array(
'bold' => true,
),
);
$objSheet->getStyle('A2:D11')->applyFromArray($style_top10);
// In du lieu vao bang
foreach ($count_views as $hang => $hd) {
for ($i = 65; $i <= 77; $i++) {
if ($i == 66 || $i == 67 || $i == 68) {
$objSheet->getStyle(chr($i).($hang+2))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
}else {
$objSheet->getStyle(chr($i).($hang+2))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
}
// $hd[chr($i)] = (!empty($hd[chr($i)])) ? $hd[chr($i)] : '';
$objSheet->getCell(chr($i).($hang+2))->setValue($hd[chr($i)]);
$objSheet->getStyle(chr($i).($hang+2))->applyFromArray($border_style);
$objSheet->getStyle(chr($i).($hang+2))->getAlignment()->setWrapText(true);
$objSheet->getStyle(chr($i).($hang+2))->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
// Set size column
// $objSheet->getColumnDimension(chr($i))->setAutoSize(false);
if ($i == 65) {
$objSheet->getColumnDimension(chr($i))->setWidth("8");
}elseif($i == 66 || $i == 67 || $i == 68) {
$objSheet->getColumnDimension(chr($i))->setWidth("26");
}else {
$objSheet->getColumnDimension(chr($i))->setWidth("12");
}
}
}
$objSheet->getStyle('A1:M1')->getAlignment()->setWrapText(true);
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="' . $filename . '.xlsx"');
PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007')->save('php://output');;
die();
} else {
redirect(base_url('backend/home/index'));
}
// Khởi tạo đối tượng PHPExcel_IOFactory để thực hiện ghi file
// ở đây mình lưu file dưới dạng excel2007header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=$fByName");
PHPExcel_IOFactory::createWriter($excel, 'Excel5')->save('php://output');
}
}
\ No newline at end of file
......@@ -36,7 +36,7 @@ class CmsTrack extends CI_Controller
//
$pageId = ($pageId == 0) ? 1 : $pageId;
//
$limit = 25;
$limit = 100;
$offset = ($pageId - 1) * $limit;
$data['offset'] = ($pageId - 1) * $limit;
$totalRecord = $this->track_model->cmsCountAll($fByName);
......
......@@ -97,6 +97,65 @@ class Track_model extends CI_Model
return $query->result_array();
}
public function getReportWeekly($week, $year, $limit = 100, $offset = 0)
{
//$sql = "SELECT * FROM report_views_weekly WHERE `week` = ? AND `year` = ? ORDER BY total_point DESC LIMIT {$offset}, {$limit} ";
//$query = $this->db->query($sql, $week, $year);
$this->db->from('report_views_weekly');
$this->db->where('week =', $week);
$this->db->where('year =', $year);
$this->db->limit($limit, $offset);
$query = $this->db->get();
return $query->result_array();
}
public function getReportMonthly($month, $year, $limit = 100, $offset = 0)
{
//$sql = "SELECT * FROM reports_views_monthly WHERE `month` = ? AND `year` = ? ORDER BY total_point DESC LIMIT {$offset}, {$limit} ";
//$query = $this->db->query($sql, $month, $year);
$this->db->from('reports_views_monthly');
$this->db->where('month =', $month);
$this->db->where('year =', $year);
$this->db->limit($limit, $offset);
$query = $this->db->get();
return $query->result_array();
}
public function getUserByTrack($track_id) {
//$query = $this->db->query("SELECT * FROM track_user WHERE track_id=?", $track_id);
//if ($query) $users = $query->result_array();
//return $users;
$this->db->from('track_user');
$this->db->where('track_id =', $track_id);
$query = $this->db->get();
return $query->result_array();
}
public function getArtistsByTrack($track_id) {
//$query = $this->db->query("SELECT * FROM track_artists WHERE track_id=?", $track_id);
//if ($query) $users = $query->result_array();
//return $users;
$this->db->from('track_artists');
$this->db->where('track_id =', $track_id);
$query = $this->db->get();
return $query->result_array();
}
public function getTrackById($id)
{
$this->db->select($this->_table . '.*');
$this->db->from($this->_table);
$this->db->where($this->_table . '.id', $id);
$query = $this->db->get();
return $query->result_array();
}
}
/* End of file welcome.php */
......
......@@ -198,6 +198,24 @@ class User_model extends CI_Model
return $result;
}
function getUser($id = null, $block = true) {
/*if ($id) {
$blockIds = ($block) ? $this->blockIds() : '0';
$query = $this->db->query("SELECT * FROM users WHERE (id=? OR email=? OR username=?) AND id NOT IN ($blockIds) AND active=?", $id,$id,$id, 1);
if ($query) $user = $query->result_array();
return $user;
} else {
return $this->authUser;
}*/
$this->db->select($this->_table . '.*');
$this->db->from($this->_table);
$this->db->where($this->_table . '.id', $id);
$query = $this->db->get();
return $query->result_array();
}
}
......
......@@ -312,7 +312,7 @@ $action = $CI->router->fetch_method();
<div class="footer">
<div class="footer-inner">
<div class="footer-content">
<span class="bigger-50">&copy; 2017</span>
<span class="bigger-50">&copy; 2020</span>
</div>
</div>
</div>
......
......@@ -22,7 +22,6 @@
<?php endif; ?>
<div class="row">
<?php echo form_open(base_url().'backend/cmsRanking/listByMonthlyAjax'); ?>
<div class="col-lg-3">
<select class="form-control" name="input-name" id="input-name">
<?php
......@@ -34,15 +33,11 @@
endforeach;
?>
</select>
<!-- <input
class="form-control" type="text"
name="input-name"
id="input-name"
placeholder="Nhập tên bài hát..."/> -->
</div>
<?php echo form_close(); ?>
<div class="col-lg-1">
<button class="btn btn-sm btn-default" id="excel">Xuất Excel</button>
<a href="" id="btn-export">
<button class="btn btn-sm btn-warning" id="excel"><i class="fa fa-download"></i> Export ra Excel</button>
</a>
</div>
</div>
<!-- /.row -->
......@@ -60,93 +55,27 @@
//Thuc hien viec ve bieu do$data
$(document).ready(function() {
var url = '<?php echo base_url("backend/cmsRanking/listByMonthlyAjax"); ?>';
var url1 = '<?php echo base_url("backend/cmsRanking/exportExcel"); ?>';
// Tìm kiếm theo cú pháp
var oldTimeout2 = '';
$('#input-name').change(function(){
updateExportLink();
clearTimeout(oldTimeout2);
oldTimeout2 = setTimeout(function(){
loadDataByAjaxFromInput(url);
}, 250);
});
$('#excel').click(function(){
exportExcel(url1);
// alert('hi');
});
changePagination('0');
updateExportLink();
});
function exportExcel(url1){
$('#data-loading').show();
var csrf_value = '<?php echo $this->security->get_csrf_hash(); ?>';
var fByName = $("#input-name").val();
//Ajax ve bieu do
$.ajax({
type: "POST",
url: url1,
data: {
csrf_name: csrf_value,
fByName: fByName
},
dataType: "text",
cache: false,
success: function(data){
$('#data-loading').hide();
changePagination('0');
}
});
}
//Ham chung cho cac input
function loadDataByAjaxFromInput(url){
$('#data-loading').show();
var csrf_value = '<?php echo $this->security->get_csrf_hash(); ?>';
var fByName = $("#input-name").val();
//Ajax ve bieu do
$.ajax({
type: "POST",
url: url,
data: {
csrf_name: csrf_value,
fByName: fByName
},
dataType: "text",
cache: false,
success: function(data){
$('#div-response').html(data);
$('#data-loading').hide();
}
});
}
//Ham chung cho cac SelectBox
function loadDataByAjaxFromSelectBox(id, url){
$('#'+id).change(function(){
$('#data-loading').show();
var csrf_value = '<?php echo $this->security->get_csrf_hash(); ?>';
var fByName = $("#input-name").val();
//Ajax ve bieu do
$.ajax({
type: "POST",
url: url,
data: {
csrf_name: csrf_value,
fByName: fByName
},
dataType: "text",
cache: false,
success: function(data){
$('#div-response').html(data);
$('#data-loading').hide();
}
});
});
}
function loadDataByAjaxDateRange(dtFrom, dtTo, url){
$('#data-loading').show();
var csrf_value = '<?php echo $this->security->get_csrf_hash(); ?>';
var fByName = $("#input-name").val();
// ajax
//Ajax
$.ajax({
type: "POST",
url: url,
......@@ -168,7 +97,7 @@
var csrf_value = '<?php echo $this->security->get_csrf_hash(); ?>';
var url = '<?php echo base_url()."backend/cmsRanking/listByMonthlyAjax"; ?>';
var fByName = $("#input-name").val();
//Ajax ve bieu do\
//Ajax
$.ajax({
type: "POST",
url: url,
......@@ -186,4 +115,9 @@
});
}
function updateExportLink() {
var href = '<?php echo base_url("backend/cmsRanking/exportReport/month"); ?>/' + $("#input-name").val();
$('#btn-export').attr('href', href);
}
</script>
\ No newline at end of file
......@@ -22,7 +22,7 @@
<?php endif; ?>
<div class="row">
<?php echo form_open(base_url().'backend/cmsRanking/listByWeeklyAjax'); ?>
<?php /*echo form_open(base_url().'backend/cmsRanking/listByWeeklyAjax'); */?>
<div class="col-lg-3">
<select class="form-control" name="input-name" id="input-name">
<?php
......@@ -36,9 +36,11 @@
</select>
</div>
<div class="col-lg-1">
<button class="btn btn-sm btn-default" id="delete-filter">Xóa bộ lọc</button>
<a href="" id="btn-export">
<button class="btn btn-sm btn-warning"><i class="fa fa-download"></i> Export ra Excel</button>
</a>
</div>
<?php echo form_close(); ?>
<?php /*echo form_close(); */?>
</div>
<!-- /.row -->
<div class="space-6"></div>
......@@ -58,12 +60,16 @@
// Tìm kiếm theo cú pháp
var oldTimeout2 = '';
$('#input-name').change(function(){
updateExportLink();
clearTimeout(oldTimeout2);
oldTimeout2 = setTimeout(function(){
loadDataByAjaxFromInput(url);
}, 250);
});
changePagination('0');
updateExportLink();
});
//Ham chung cho cac input
function loadDataByAjaxFromInput(url){
......@@ -153,5 +159,10 @@
}
});
}
function updateExportLink() {
var href = '<?php echo base_url("backend/cmsRanking/exportReport/week"); ?>/' + $("#input-name").val();
$('#btn-export').attr('href', href);
}
</script>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment