<?php
/**
 * PHPExcel
 *
 * Copyright (c) 2006 - 2015 PHPExcel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category   PHPExcel
 * @package    PHPExcel
 * @copyright  Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt	LGPL
 * @version    ##VERSION##, ##DATE##
 */

include_once("../../../php/sessionStart.php"); 
include_once("../../../php/db/dbExec.php");
include_once('../../../php/functions.php');
include_once("../../../php/fpdf/functions.php");
include_once('../../../php/maxExecTime.php');

$empCod = $_SESSION['empCod'];
$empNom = $_SESSION['empNom'];

$selDepto=$_GET["selDepto"];
$selsubDepto=$_GET["selSubDepto"];
$selBodega=$_GET["selBodega"];
$BodegaNom=$_GET["BodegaNom"];
$dtFeci=$_GET["dtFeci"];
$dtFecf=$_GET["dtFecf"];

# QUERYS
if ($selDepto=='0000') {
    if ($selsubDepto=='0000') {
        $sArtic = "SELECT *, TRIM(art_cod) AS art_cod,
                    TRIM(art_desc) AS art_desc,
                    TRIM(art_desd) AS art_desd,
                    TRIM(art_marca) AS art_marca,
                    TRIM(art_prov) AS art_prov,
                    TRIM(art_codf) AS art_codf,
                    TRIM(art_codbarr) AS art_codbarr
                    FROM artic art LEFT JOIN deptosi di ON art.art_dep=di.dep_cod 
                    LEFT JOIN subdeptosi sdi ON art.art_dep=sdi.sdep_dep AND art.art_subdep=sdi.sdep_cod
                    LEFT JOIN unimed um ON art.art_medi=um.um_cod
                    INNER JOIN exiart ea ON art.art_emp=ea.ea_emp AND art.art_cod=ea.ea_cod
                    WHERE art_emp='$empCod' AND art_bienser='B' GROUP BY art.art_emp,art.art_cod ORDER BY art_emp,art_dep,art_subdep,art_desc";
    } else {
        $sArtic = "SELECT *, TRIM(art_cod) AS art_cod,
                    TRIM(art_desc) AS art_desc,
                    TRIM(art_desd) AS art_desd,
                    TRIM(art_marca) AS art_marca,
                    TRIM(art_prov) AS art_prov,
                    TRIM(art_codf) AS art_codf,
                    TRIM(art_codbarr) AS art_codbarr
                    FROM artic art LEFT JOIN deptosi di ON art.art_dep=di.dep_cod 
                    LEFT JOIN  subdeptosi sdi ON art.art_dep=sdi.sdep_dep AND art.art_subdep=sdi.sdep_cod
                    LEFT JOIN unimed um ON art.art_medi=um.um_cod
                    INNER JOIN exiart ea ON art.art_emp=ea.ea_emp AND art.art_cod=ea.ea_cod
                    WHERE art_emp='$empCod' AND art_subdep='$selsubDepto' AND art_bienser='B' GROUP BY art.art_emp,art.art_cod ORDER BY art_emp,art_dep,art_subdep,art_desc";
    }
} else {
    if ($selsubDepto=='0000') {
        $sArtic = "SELECT *, TRIM(art_cod) AS art_cod,
                    TRIM(art_desc) AS art_desc,
                    TRIM(art_desd) AS art_desd,
                    TRIM(art_marca) AS art_marca,
                    TRIM(art_prov) AS art_prov,
                    TRIM(art_codf) AS art_codf,
                    TRIM(art_codbarr) AS art_codbarr
                    FROM artic art LEFT JOIN deptosi di ON art.art_dep=di.dep_cod 
                    LEFT JOIN  subdeptosi sdi ON art.art_dep=sdi.sdep_dep AND art.art_subdep=sdi.sdep_cod
                    LEFT JOIN unimed um ON art.art_medi=um.um_cod
                    INNER JOIN exiart ea ON art.art_emp=ea.ea_emp AND art.art_cod=ea.ea_cod
                    WHERE art_emp='$empCod' AND art_dep='$selDepto' AND art_bienser='B' GROUP BY art.art_emp,art.art_cod ORDER BY art_emp,art_dep,art_subdep,art_desc";
    } else {
        $sArtic = "SELECT *, TRIM(art_cod) AS art_cod,
                    TRIM(art_desc) AS art_desc,
                    TRIM(art_desd) AS art_desd,
                    TRIM(art_marca) AS art_marca,
                    TRIM(art_prov) AS art_prov,
                    TRIM(art_codf) AS art_codf,
                    TRIM(art_codbarr) AS art_codbarr
                    FROM artic art LEFT JOIN deptosi di ON art.art_dep=di.dep_cod 
                    LEFT JOIN  subdeptosi sdi ON art.art_dep=sdi.sdep_dep AND art.art_subdep=sdi.sdep_cod
                    LEFT JOIN unimed um ON art.art_medi=um.um_cod
                    INNER JOIN exiart ea ON art.art_emp=ea.ea_emp AND art.art_cod=ea.ea_cod
                    WHERE art_emp='$empCod' AND art_dep='$selDepto' AND art_subdep='$selsubDepto' AND art_bienser='B' GROUP BY art.art_emp,art.art_cod ORDER BY art_emp,art_dep,art_subdep,art_desc";
    }
}

function sExiart($codd) { 
    global $empCod, $usuNom, $selBodega;
    return "SELECT * FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$selBodega'";
}

function sExiartTodas($codd) { 
    global $empCod, $usuNom, $selBodega;
    return "SELECT *, SUM(ea_exist) AS ea_existtot FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$codd' GROUP BY '$empCod','$codd'";
}

function sMoviie0($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFeci;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
            SUM(mov_entra) AS mov_sentra
            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodent='$selBodega' AND mov_fec>='$dtFeci' GROUP BY '$empCod','$codd'";
}
function sMoviis0($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFeci;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
            SUM(mov_sale) AS mov_ssale
            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodsal='$selBodega' AND mov_fec>='$dtFeci' GROUP BY '$empCod','$codd'";
}

function sMoviie0Todas($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFeci;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
            SUM(mov_entra) AS mov_sentra
            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_fec>='$dtFeci' GROUP BY '$empCod','$codd'";
}
function sMoviis0Todas($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFeci;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
            SUM(mov_sale) AS mov_ssale
            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_fec>='$dtFeci' GROUP BY '$empCod','$codd'";
}

function sCierrei($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFecf ;
    return "SELECT * FROM cierresi WHERE ci_emp='$empCod' AND ci_cod='$codd' AND ci_fec='$dtFecf'";
}

function sCierreiTodas($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFecf;
    return "SELECT * FROM cierresi WHERE ci_emp='$empCod' AND ci_cod='$codd' AND ci_fec='$dtFecf'";
}

function sMoviie0c($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFeci, $dtFecf;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,td_afecos,td_inveini, 
            SUM(mov_entra) AS mov_sentra
            FROM movii LEFT JOIN tipodoci ON movii.mov_tipo=tipodoci.td_cod WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodent='$selBodega' AND mov_fec>='$dtFeci' AND mov_fec<='$dtFecf' AND td_afecos='S' AND td_inveini='N' GROUP BY '$empCod','$codd'";
}
function sMoviie0cTodas($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFeci, $dtFecf;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,td_afecos,td_inveini,
            SUM(mov_entra) AS mov_sentra
            FROM movii LEFT JOIN tipodoci ON movii.mov_tipo=tipodoci.td_cod WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_fec>='$dtFeci' AND mov_fec<='$dtFecf' AND td_afecos='S' AND td_inveini='N' GROUP BY '$empCod','$codd'";
}
function sMoviie0o($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFeci, $dtFecf;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,td_afecos,td_inveini,
            SUM(mov_entra) AS mov_sentra
            FROM movii LEFT JOIN tipodoci ON movii.mov_tipo=tipodoci.td_cod WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodent='$selBodega' AND mov_fec>='$dtFeci' AND mov_fec<='$dtFecf' AND (td_afecos!='S' OR td_inveini='S' OR td_inveini='P')  GROUP BY '$empCod','$codd'";
}
function sMoviie0oTodas($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFeci, $dtFecf;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,td_afecos,td_inveini,
            SUM(mov_entra) AS mov_sentra
            FROM movii LEFT JOIN tipodoci ON movii.mov_tipo=tipodoci.td_cod WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_fec>='$dtFeci' AND mov_fec<='$dtFecf' AND (td_afecos!='S' OR td_inveini='S' OR td_inveini='P') GROUP BY '$empCod','$codd'";
}

function sMoviis0v($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFeci, $dtFecf;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,td_repven,
            SUM(mov_sale) AS mov_ssale
            FROM movii LEFT JOIN tipodoci ON movii.mov_tipo=tipodoci.td_cod WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodsal='$selBodega' AND mov_fec>='$dtFeci' AND mov_fec<='$dtFecf' AND td_repven='S' GROUP BY '$empCod','$codd'";
}
function sMoviis0vTodas($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFeci, $dtFecf;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,td_repven,
            SUM(mov_sale) AS mov_ssale
            FROM movii LEFT JOIN tipodoci ON movii.mov_tipo=tipodoci.td_cod WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_fec>='$dtFeci' AND mov_fec<='$dtFecf' AND td_repven='S' GROUP BY '$empCod','$codd'";
}
function sMoviis0o($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFeci, $dtFecf;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,td_repven,
            SUM(mov_sale) AS mov_ssale
            FROM movii LEFT JOIN tipodoci ON movii.mov_tipo=tipodoci.td_cod WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodsal='$selBodega' AND mov_fec>='$dtFeci' AND mov_fec<='$dtFecf' AND td_repven!='S' GROUP BY '$empCod','$codd'";
}
function sMoviis0oTodas($codd) { 
    global $empCod, $usuNom, $selBodega, $dtFeci, $dtFecf;
    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,td_repven,
            SUM(mov_sale) AS mov_ssale
            FROM movii LEFT JOIN tipodoci ON movii.mov_tipo=tipodoci.td_cod WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_fec>='$dtFeci' AND mov_fec<='$dtFecf' AND td_repven!='S' GROUP BY '$empCod','$codd'";
}

# EJECUCION DE QUERYS
$db = new dbExec();

$func = new functions();

$select["artic"] = $db->query($sArtic);

/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');

if (PHP_SAPI == 'cli')
	die('This example should only be run from a Web Browser');

require_once dirname(__FILE__) . '/../../../php/PHPExcel/Classes/PHPExcel.php';

$iIni=0;
$objPHPExcel = new PHPExcel();

# CREAR HOJAS
for ($i=0; $i < 1; $i++) { 
	$objPHPExcel->createSheet();
}

# HOJAS
$sheet['articulos']=0;

# ESTABLECER PROPIEDADES DEL DOCUMENTO
$objPHPExcel->getProperties()->setCreator("Asesoría en Sistemas, S.A.")
						->setLastModifiedBy("Asesoría en Sistemas, S.A.")
						->setTitle("Office 2007 XLSX Test Document")
						->setSubject("Office 2007 XLSX Test Document")
						->setDescription("")
						->setKeywords("office 2007 openxml php")
						->setCategory("Contabilidad General");

# ENCABEZADO PRIMER HOJA
$i=$iIni;
$j=6;
$objPHPExcel->setActiveSheetIndex($sheet['articulos'])
			->setCellValueByColumnAndRow($i, 1, $empNom)
			->setCellValueByColumnAndRow($i, 2, "Resumen de entradas y salidas del ".strftime("%d/%m/%Y", strtotime($dtFeci))." al ".strftime("%d/%m/%Y", strtotime($dtFecf)))
            ->setCellValueByColumnAndRow($i, 3, "Bodega:  ".$BodegaNom)
			->setCellValueByColumnAndRow($i++, $j, 'Familia')
			->setCellValueByColumnAndRow($i++, $j, 'SubFamilia')
			->setCellValueByColumnAndRow($i++, $j, 'Codigo')
			->setCellValueByColumnAndRow($i++, $j, 'Descripcion')
			->setCellValueByColumnAndRow($i++, $j, 'Medida')
			->setCellValueByColumnAndRow($i++, $j, 'Existencia Inicial')
			->setCellValueByColumnAndRow($i++, $j, '  Compras')
            ->setCellValueByColumnAndRow($i++, $j, '  Otras/Entradas')
            ->setCellValueByColumnAndRow($i++, $j, '  Ventas')
            ->setCellValueByColumnAndRow($i++, $j, '  Otras/Salidas')
            ->setCellValueByColumnAndRow($i++, $j, 'Existencia Final')
            ->setCellValueByColumnAndRow($i++, $j, 'Costo Total');
# ESTILO ENCABEZADO PRIMERA HOJA
$styEmp = array(
    'font' => array(
        'bold' => true,
        'size' => 17,
    ),
    'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$styFec = array(
	'alignment' => array(
        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    )
);

$styEncabezado = array(
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);

$bordersThin = array(
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);

$borderBottomDouble = array(
    'borders' => array(
        'bottom' => array(
            'style' => PHPExcel_Style_Border::BORDER_DOUBLE
        )
    )
);

$borderTopThin = array(
    'borders' => array(
        'top' => array(
            'style' => PHPExcel_Style_Border::BORDER_THIN
        )
    )
);


foreach(range('A','T') as $colID) { 
    $objPHPExcel->getActiveSheet()->getColumnDimension($colID)->setAutoSize(true); 
}

$objPHPExcel->getActiveSheet()->mergeCells('A1:L1')->getStyle('A1')->applyFromArray($styEmp);
$objPHPExcel->getActiveSheet()->mergeCells('A2:L2')->getStyle('A2')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->mergeCells('A3:L3')->getStyle('A3')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->mergeCells('A4:L4')->getStyle('A4')->applyFromArray($styFec);
$objPHPExcel->getActiveSheet()->getStyle('A6:L6')->applyFromArray($styEncabezado);

# VALORES PRIMER HOJA
$i=$iIni;
for ($j=7; $rec = $db->fetchAssoc($select['artic']); $j++) {

    $codd=$rec["art_cod"];

    $cosp=$rec["art_cosp"];

    if ($selBodega=='0000') {
        $select["exiart"] = $db->query(sExiartTodas($codd));
        $fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
        $Exist = $fetchAssoc["exiart"]["ea_existtot"];

        $select["cierresi"] = $db->query(sCierreiTodas($codd));
        $fetchAssoc["cierresi"] = $db->fetchAssoc($select["cierresi"]);
        if ($db->numRows($select["cierresi"]) > 0) {
            $cosp = $fetchAssoc["cierresi"]["ci_cosp"];
        }
        $select["movii"] = $db->query(sMoviie0Todas($codd));
        $recme0 = $db->fetchAssoc($select['movii']);
        $sEntramov=$recme0["mov_sentra"];

        $select["movii"] = $db->query(sMoviis0Todas($codd));
        $recms0 = $db->fetchAssoc($select['movii']);
        $sSalemov=$recms0["mov_ssale"];

        $Exiini=($Exist-$sEntramov)+$sSalemov;

        $select["movii"] = $db->query(sMoviie0cTodas($codd));
        $recme0c = $db->fetchAssoc($select['movii']);
        $sEntramovcom=$recme0c["mov_sentra"];

        $select["movii"] = $db->query(sMoviie0oTodas($codd));
        $recme0o = $db->fetchAssoc($select['movii']);
        $sEntramovotr=$recme0o["mov_sentra"];

        $select["movii"] = $db->query(sMoviis0vTodas($codd));
        $recms0v = $db->fetchAssoc($select['movii']);
        $sSalemovven=$recms0v["mov_ssale"];

        $select["movii"] = $db->query(sMoviis0oTodas($codd));
        $recms0o = $db->fetchAssoc($select['movii']);
        $sSalemovotr=$recms0o["mov_ssale"];

    } else {
        $select["exiart"] = $db->query(sExiart($codd));
        $fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
        $Exist = $fetchAssoc["exiart"]["ea_exist"];

        $select["cierresi"] = $db->query(sCierrei($codd));
        $fetchAssoc["cierresi"] = $db->fetchAssoc($select["cierresi"]);
        if ($db->numRows($select["cierresi"]) > 0) {
            $cosp = $fetchAssoc["cierresi"]["ci_cosp"];
        }
        $select["movii"] = $db->query(sMoviie0($codd));
        $recme0 = $db->fetchAssoc($select['movii']);
        $sEntramov=$recme0["mov_sentra"];

        $select["movii"] = $db->query(sMoviis0($codd));
        $recms0 = $db->fetchAssoc($select['movii']);
        $sSalemov=$recms0["mov_ssale"];

        $Exiini=($Exist-$sEntramov)+$sSalemov;

        $select["movii"] = $db->query(sMoviie0c($codd));
        $recme0c = $db->fetchAssoc($select['movii']);
        $sEntramovcom=$recme0c["mov_sentra"];

        $select["movii"] = $db->query(sMoviie0o($codd));
        $recme0o = $db->fetchAssoc($select['movii']);
        $sEntramovotr=$recme0o["mov_sentra"];

        $select["movii"] = $db->query(sMoviis0v($codd));
        $recms0v = $db->fetchAssoc($select['movii']);
        $sSalemovven=$recms0v["mov_ssale"];

        $select["movii"] = $db->query(sMoviis0o($codd));
        $recms0o = $db->fetchAssoc($select['movii']);
        $sSalemovotr=$recms0o["mov_ssale"];

    }
    $Exifin=$Exiini+($sEntramovcom+$sEntramovotr)-($sSalemovven+$sSalemovotr);

    if ($Exiini==0 && $sEntramovcom==0 && $sEntramovotr==0 && $sSalemovven==0 && $sSalemovotr==0) {
        $j=$j-1;
        continue;
    }        
    $costot=round($Exifin*$cosp,5);

	$objPHPExcel->getActiveSheet()
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['dep_nom'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['sdep_nom'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_cod'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['art_desc'])))
				->setCellValueByColumnAndRow($i++, $j, utf8_encode(trim($rec['um_nom'])))
				->setCellValueByColumnAndRow($i++, $j, $Exiini)
				->setCellValueByColumnAndRow($i++, $j, $sEntramovcom)
                ->setCellValueByColumnAndRow($i++, $j, $sEntramovotr)
                ->setCellValueByColumnAndRow($i++, $j, $sSalemovven)
                ->setCellValueByColumnAndRow($i++, $j, $sSalemovotr)
                ->setCellValueByColumnAndRow($i++, $j, $Exifin)
                ->setCellValueByColumnAndRow($i++, $j, $costot);
	$i=$iIni;
}

// TOTALES DEL MOVIMIENTO
$objPHPExcel->getActiveSheet()->getStyle('K'.$j.':L'.$j)->applyFromArray($borderTopThin);
$objPHPExcel->getActiveSheet()->getStyle('K'.$j.':L'.$j)->applyFromArray($borderBottomDouble);

$objPHPExcel->getActiveSheet()
    ->setCellValueByColumnAndRow(10, $j, 'Total')
    ->setCellValueByColumnAndRow(11, $j, '=SUM(L7:L'.($j-1).')'); 

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(25);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(45);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20);
$objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);

$objPHPExcel->getActiveSheet()->getStyle('F5'.':K'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00');
$objPHPExcel->getActiveSheet()->getStyle('L5'.':L'.$j)->getNumberFormat()->setFormatCode('###,###,##0.00000');
$objPHPExcel->getActiveSheet()->getStyle('A5'.':E'.$j)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);

# ESTABLECER TITULOS
$objPHPExcel->setActiveSheetIndex($sheet['articulos'])->setTitle('articulos');

# AL ABRIR EL DOCUMENTO ABRIR EN PRIMERA HOJA
$objPHPExcel->setActiveSheetIndex(0);

$db->close();

// Redirect output to a client’s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="ResuMov.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;

?>