In chart.js print graphics in a csv or Excel

0

Hello colleagues, I am trying to print my graphic in an excel (xlsx or csv) the problem is that I have only found that only the data of the table is printed but not the graph as such. So I would like to know if there is any way or I have to use another type of plugin so that I can do this, for now all I want to print is this:

<script>
	var cadena = "";
	var datos = "";
	var respuestas = "";
	var datosSeparados = "";
	var downloadBtn = document.getElementById('downloadBtn');
	var canvas = document.getElementById("Graf01");
	var frecuencias = [];
	$(document).ready(function(){
		@foreach($preguntas as $p)
		var respuestas{{$p->id_pesp}} = [];
		@if($p->tipo != "1" && $p->tipo != "2")
		if($("#graf{{$p->id_pesp}}")){
			cadena = ""
			@foreach($resultados as $res)
				@if($res->id_pesp == $p->id_pesp)
				cadena += "{{$res->respuesta}};";
				@endif
			@endforeach
			datos = cadena.substring(0, cadena.length - 1);
			alert(datos);
			datosSeparados = datos.split(';');
			@foreach($respuestas as $r)
			var f = 0;
			@if($r->id_pesp == $p->id_pesp)
				respuestas{{$p->id_pesp}}.push("{{$r->respuestas}}");
				for(var i = 0; i < datosSeparados.length; i++){
					if(datosSeparados[i]=={{$r->id_res}}){
						f++;
					}
				}
				frecuencias.push(f);
			@endif
			@endforeach
			var grafica = $('#graf{{$p->id_pesp}}');

			var grafica = new Chart(canvas, {
				type: 'doughnut',
				data: {
			        labels: respuestas{{$p->id_pesp}},
			        datasets: [{
			            label: 'Encuesta Especifica',
			            data: frecuencias,
			            lineTension: 0,
				            backgroundColor: [
			                'rgba(255, 99, 132, 0.2)',
			                'rgba(54, 162, 235, 0.2)',
			                'rgba(255, 206, 86, 0.2)',
			                'rgba(75, 192, 192, 0.2)',
			                'rgba(153, 102, 255, 0.2)',
			                'rgba(255, 159, 64, 0.2)'
			            ],
			            borderColor: [
			                'rgba(255, 99, 132, 1)',
			                'rgba(54, 162, 235, 1)',
			                'rgba(255, 206, 86, 1)',
			                'rgba(75, 192, 192, 1)',
			                'rgba(153, 102, 255, 1)',
			                'rgba(255, 159, 64, 1)'
			            ],
			            borderWidth: 1
			        }]
			    }
			});
		}
		@endif
		@endforeach

I got it in PDF but missing the Excel part, thanks for your help,

    
asked by Dohko19 11.07.2018 в 18:52
source

1 answer

1

You can do it by using the library Laravel-Excel in its version 2.1

The logic would be to create the excel, pass the data to it and then select that data and create the corresponding graphics.

I'll give you an example so you can guide yourself, this could be a function in a controller to call to create the excel:

public function export(Request $request)
{
    //nombre del archivo
    $name = date("Y-m-d H-i-s");

    //de alguna manera obetenes los datos, supongamos tenemos una Collection de items como la siguiente
    $datosDelGrafico = [
        {
            "nombre": "Reloj",
            "total": 50
        },
        {
            "nombre": "Cartera",
            "total": 25
        },
        {
            "nombre": "Bolse",
            "total": 75
        },
    ]

    $excel = Excel::create($name, function($excel) use (datosDelGrafico) {

        $excel->sheet('Worksheet', function($sheet) use (datosDelGrafico) {

            $datos = array(
                array("Producto", "Cantidad")
            );

            foreach ($datosDelGrafico as $producto){
                $data= array($producto->nombre, $producto->total);
                array_push($datos, $data);
            }

            //agregamos los datos al excel
            $sheet->fromArray($datos, null, 'A1', false, false);


            //seleccionamos el campo que tiene la leyenda, "Cantidad" en la celda B1
            $dataSeriesLabels = array(
                new \PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$B$1', NULL, 1),
            );

            //seleccionamos las categorias en este caso reloj, cartera, etc que que para este ejemplo se encuentran en A2 hasta A4
            $xAxisTickValues = array(
                new \PHPExcel_Chart_DataSeriesValues('String', 'Worksheet!$A$2:$A$4', NULL, 10),
            );

            //seleccionamos los valores totales que para este ejemplo se encuentran en B2 hasta B4
            $dataSeriesValues = array(
                new \PHPExcel_Chart_DataSeriesValues('Number', 'Worksheet!$B$2:$B$4', NULL, 10),
            );


            //todo lo que sigue crea el chart en base a lo que seleccionamos anteriormente
            $layout = new \PHPExcel_Chart_Layout();
            $layout->setShowVal(TRUE);

            $ChartGroupType = NULL;
            $yAxis = NULL;

            $chartType = \PHPExcel_Chart_DataSeries::TYPE_BARCHART;
            $layout->setShowPercent(TRUE);

            $ChartGroupType = \PHPExcel_Chart_DataSeries::GROUPING_STANDARD;

            $yAxis = new \PHPExcel_Chart_Axis();
            $yAxis->setAxisOptionsProperties(
                \PHPExcel_Chart_Axis::AXIS_LABELS_NEXT_TO,
                null,
                null,
                \PHPExcel_Properties::ORIENTATION_REVERSED
            );

            $series = new \PHPExcel_Chart_DataSeries(
                $chartType,                                 //          plotType
                $ChartGroupType,                            //          tipo de agrupamiento
                range(0, count($dataSeriesValues)-1),       //          plotOrder
                $dataSeriesLabels,                          //          plotLabel
                $xAxisTickValues,                           //          plotCategory
                $dataSeriesValues                           //          plotValues
            );

            $series->setPlotDirection(\PHPExcel_Chart_DataSeries::DIRECTION_VERTICAL);

            $plotArea = new \PHPExcel_Chart_PlotArea($layout, array($series));
            $legend = new \PHPExcel_Chart_Legend(\PHPExcel_Chart_Legend::POSITION_RIGHT, NULL, false);
            $title = new \PHPExcel_Chart_Title("titulo del chart");

            $chart = new \PHPExcel_Chart(
                "nombredechart",    //          name
                $title,             //          title
                $legend,            //          legend
                $plotArea,          //          plotArea
                true,               //          plotVisibleOnly
                0,                  //          displayBlanksAs
                null,               //          xAxisLabel
                null,               //          yAxisLabel
                NULL,               //          xAxis
                $yAxis              //          yAxis
            );

            //seteamos en que posicion queremos que se vea el chart
            $chart->setTopLeftPosition('D1');
            $chart->setBottomRightPosition('J10');ç

            //lo agregamos al excel.
            $sheet->addChart($chart);
        });
    });

    //le podemos setear alguna info
    $excel->setTitle('Un titulo');
    $excel->setCreator('tu nombre');
    $excel->setCompany('tu empresa');
    $excel->setDescription('Datos exportados de seccion Cultura');


    //a partir de aca hacemos lo que nos parezca, por ejemplo lo guardamos
    $excel->store('xlsx', storage_path('app/public/excel'), true);

    //o iniciamos la descarga
    $excel->download('xlsx');
}

I hope it's helpful, greetings!

    
answered by 20.07.2018 / 16:38
source