Joomla Exporting Or Downloading Reports To CSV - excel

I have the following code in my inventory section when i run this code it save an excel file but the result showing the whole html file not my data.
<?php
$csv = NULL;
$arr = array("product_name","product_sku","product_in_stock","virtuemart_product_id","product_price_display","product_instock_value");
$csv = "Product Name, Product SKU, In Stock, Booked ordered products, Cost Price, Stock Value \n";
$c=0;
while(list($key,$value)=each($arr)){
$c++;
$cc=1;
foreach ($this->inventorylist as $key => $product){
$cc++;
$csv .= join(',',array($product->product_name.",".$product->product_sku.",".$product->product_in_stock.",".$product->virtuemart_product_id.",".$product->product_price_display.",".$product->product_instock_value))." \n";
}
}
JResponse::clearHeaders();
JResponse::setHeader('Content-Type', 'application/vnd.ms-excel', true);
JResponse::setHeader('Content-Disposition', 'csv; filename=inventory_report.csv; size='.strlen($csv), true);
JResponse::sendHeaders();
Any help will be appreciated.
Thanks
Khalique

Here's the brute force solution just to get you going:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
// Echo the csv content.
echo "foo,bar\n1,2";
// Close the application gracefully.
JFactory::getApplication()->close();
A slightly cleaner way without using views, but including &format=raw in the URL is:
$app = JFactory::getApplication();
$doc = JFactory::getDocument();
$doc->setMimeEncoding('application/vnd.ms-excel');
$app->setHeader(
'Content-disposition',
'attachment; filename="inventory_report.csv"',
true
);
echo "foo,bar\n1,2";
But the best way is to use a download view based on the raw document type. You can find an example of this in com_banners:
Controller: https://github.com/joomla/joomla-cms/blob/staging/administrator/components/com_banners/controllers/tracks.raw.php
View: https://github.com/joomla/joomla-cms/blob/staging/administrator/components/com_banners/views/tracks/view.raw.php
You might also gain some extra insight from this discussion https://groups.google.com/forum/#!topic/joomla-dev-general/dRa_39AGDBY

Related

Laravel Excel Import Write into Batches of Excel file

I have a large number of records in an excel sheet which is taking too much time while importing to the 3 tables in database. To overcome this issue, I am trying to import it through batch by creating small excel files with less data so that I run queue jobs of laravel on it. I am trying with the below code but it doesn't work, it throws an error of Array to String conversion and also sub excel files are not creating. I am using excel Maatweb, but I am handling it through controller.
Can someone lead me please.
function importBatchFiles(Request $request)
{
$this->validate($request, [
'file' => 'required|mimes:xls,xlsx,csv'
]);
$file = $request->file('file');
//$fileName='orders_'.$request->get('company_id').'_'.date('Y-m-d').uniqid().'.xlsx';
if ($file->isValid()) {
//$file->move('order_list', $fileName);
$data = Excel::toArray(new OrdersImport, request()->file('file'));
foreach($data as $key => $value)
{
foreach($value as $row)
{
$inputs[] = $row;
}
}
$data1 = array_slice($inputs, 1);
$parts = (array_chunk($data1, 500));
foreach($parts as $index => $part){
$filename = resource_path('pending-files/'.date('Y-m-d').$index.'.'.$request->file->extension());
file_put_contents($filename, $part);
}
return Response::json(['success' => 'Orders Queued for importing.']);
}else{
return Response::json(['error' => 'Some errror']);
}
}
When using the WithChunkReading concern, you can execute each chunk into a queue job. You can do so by simply adding the ShouldQueue contract.
For more details please refer to this link: https://docs.laravel-excel.com/3.1/imports/queued.html

Chunk and excel Laravel

guys.
I need help with this code. I need to download an excel with arround 550000 records. So i was wondering how can i use eloquent with chunk, skip and limit and get to make the excel or do something better than this. I started to making some code to save excel in a folder and then download in a zip, but i cant make works chunk and get.
I had problems with time execution and memory limit, but thats no more a problem.
This is my code.
$x=1;
for ($i=0; $i<=550000; $i=$i+15000) {
$personas="";
$personas = DB::table("cat_personas as c")->select("c.*","s.seccion","ca.casilla")
->leftJoin("cat_casillas as ca","c.cat_casilla_id","=","ca.id")
->join("cat_seccion as s","c.cat_seccion_id","=","s.id")
->where($filtros)
->whereRaw("c.id NOT IN ( SELECT cruzado FROM registro_persona )")
->whereRaw($whereCadena)
->orderby('c.consecutivo')
->orderby('c.apellido_paterno')
->orderby('c.apellido_materno')
->orderby('c.nombre')
->orderby('s.seccion')
->orderby('ca.casilla')
->skip($i)->limit(15000);
//$personas=$personas->get();
dd($personas->count());
if($personas->count()>0){
$spreadsheet = new Spreadsheet();
$r=1;
$sheet = $spreadsheet->getActiveSheet()
->setCellValue('A'.$r, '#')
->setCellValue('B'.$r, 'NOMBRE')
->setCellValue('C'.$r, 'APELLIDO PATERNO')
->setCellValue('D'.$r, 'APELLIDO MATERNO')
->setCellValue('E'.$r, 'SECCION')
->setCellValue('F'.$r, 'CASILLA')
->setCellValue('G'.$r, 'CONSECUTIVO');
$r++;
$personas->chunk(5000, function($personas) use (&$spreadsheet,&$r,&$sheet) {
$c=1;
//dd($personas->count());
foreach ($personas as $key) {
$sheet = $spreadsheet->getActiveSheet()
->setCellValue('A'.$r, $c)
->setCellValue('B'.$r, $key->nombre)
->setCellValue('C'.$r, $key->apellido_paterno)
->set`enter code here`CellValue('D'.$r, $key->apellido_materno)
->setCellValue('E'.$r, $key->seccion)
->setCellValue('F'.$r, $key->casilla)
->setCellValue('G'.$r, $key->consecutivo);
$r++;
$c++;
}
});
$writer = new Xlsx($spreadsheet);
//header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//header('Content-Disposition: attachment; filename="personas.xlsx"');
$writer->save($path."/personas$x.xlsx");
$x++;
}
}
You can use chunk() this way.
$personas = DB::table("cat_personas as c")->select("c.*","s.seccion","ca.casilla")
->leftJoin("cat_casillas as ca","c.cat_casilla_id","=","ca.id")
->join("cat_seccion as s","c.cat_seccion_id","=","s.id")
->where($filtros)
->whereRaw("c.id NOT IN ( SELECT cruzado FROM registro_persona )")
->whereRaw($whereCadena)
->orderby('c.consecutivo')
->orderby('c.apellido_paterno')
->orderby('c.apellido_materno')
->orderby('c.nombre')
->orderby('s.seccion')
->orderby('ca.casilla');
$spreadsheet = new Spreadsheet();
$r = 1;
$sheet = $spreadsheet->getActiveSheet()
->setCellValue('A'.$r, '#')
->setCellValue('B'.$r, 'NOMBRE')
->setCellValue('C'.$r, 'APELLIDO PATERNO')
->setCellValue('D'.$r, 'APELLIDO MATERNO')
->setCellValue('E'.$r, 'SECCION')
->setCellValue('F'.$r, 'CASILLA')
->setCellValue('G'.$r, 'CONSECUTIVO');
$r++;
$c = 1;
$personas->chunk(500, function($personae) use ($spreadsheet, $r, $c) {
foreach ($personae as $persona) {
$spreadsheet->getActiveSheet()
->setCellValue('A'.$r, $c)
->setCellValue('B'.$r, $persona->nombre)
->setCellValue('C'.$r, $persona->apellido_paterno)
->setCellValue('D'.$r, $persona->apellido_materno)
->setCellValue('E'.$r, $persona->seccion)
->setCellValue('F'.$r, $persona->casilla)
->setCellValue('G'.$r, $persona->consecutivo);
$r++;
$c++;
}
});
$writer = new Xlsx($spreadsheet);
$writer->save($path . "/personas.xlsx");
There might be an issue with the total size of the spreadsheet, but if so, this should be a good start towards finding that solution.
PS - This is untested.

Empty PHPExcel file using liuggio/ExcelBundle in Symfony

I have some code that iterates over the rows and columns of an Excel sheet and replaces text with other text. This is done with a service that has the excel file and a dictionary as parameters like this.
$mappedTemplate = $this->get('app.entity.translate')->translate($phpExcelObject, $dictionary);
The service itself looks like this.
public function translate($template, $dictionary)
{
foreach ($template->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
if (!is_null($cell->getCalculatedValue())) {
if (array_key_exists((string)$cell->getCalculatedValue(), $dictionary)) {
$worksheet->setCellValue(
$cell->getCoordinate(),
$dictionary[$cell->getCalculatedValue()]
);
}
}
}
}
}
}
return $template;
}
After some debugging I found out that the text actually is replaced and that the service works like it should. The problem is that when I return the new PHPExcel file as a response to download, the excel is empty.
This is the code I use to return the file.
// create the writer
$writer = $this->get('phpexcel')->createWriter($mappedTemplate, 'Excel5');
// create the response
$response = $this->get('phpexcel')->createStreamedResponse($writer);
// adding headers
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$file_name
);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
return $response;
What am I missing?
Your code is missing the calls to the writer.
You only create the writer, but never use it, at least not in your shared code examples:
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$response = $this->get('phpexcel')->createStreamedResponse($objWriter)
Another thing is the content type: Do you have the apache content types setup correctly?
$response->headers->set('Content-Type', 'application/vnd.ms-excel; charset=utf-8');

prevent direct access to PDF link for guest users

I have a joomla site. And have some pdf files into the root of the website.
Is there a way to protect the DIRECT ACCESS to the pdf's for the GUESTS(public) users.. and allow for REGISTERED users?
I tried with htaccess(deny) but registered users can't view the pdf directly too..
Searched but didn't find nothing about this.. PLEASE can somebody help.
Thank you
You must use document management plug-in if you wont want to write your own php codes.SO, DOCman is a powerful document management solution for Joomla. You can check it from following link.
http://extensions.joomla.org/extensions/directory-a-documentation/downloads/10958
Create a file called download.php
Add the following code to download.php file enclose with php tag
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
if (file_exists(dirname(__FILE__) . '/defines.php')) {
include_once dirname(__FILE__) . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', dirname(__FILE__));
require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
// Mark afterLoad in the profiler.
JDEBUG ? $_PROFILER->mark('afterLoad') : null;
// Instantiate the application.
$app = JFactory::getApplication('site');
// Initialise the application.
$app->initialise();
$user = JFactory::getUser();
$getfile = JRequest::getVar('file',null,'get','string');
if($getfile){
if($user->get('id') == 0){
die('permission denied');
}
$link = "/files/".$getfile.".pdf"; // Locate the pdf file
$file = JPATH_SITE.$link;
header("Content-Type: application/octet-stream");
$filename = $getfile.'.pdf';
header("Content-Disposition: attachment; filename=".urlencode($filename));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
}
$app->close();
URL example :- www.example.com/download.php?file=filename
And make sure you have change the $link variable as you need.
In .htacess file you have to add the following code
deny from all
And it should be located under the invoice folder where the pdf files is located.
If you use deny from all then file do not have download access for the particular directory where the htacess file is located.
To allow download access for registered user the below controller has to be called instead of direct file path url.
URL example :- www.example.com/index.php?option=com_temp&task=temp.downloadmypdf&file=filename
public function downloadmypdf(){
$user = JFactory::getUser();
$getfile = JRequest::getVar('file');
if($user->get('id') == 0){
die('permission denied');
}
$link = "/invoice/".$getfile.".pdf";
$file = JPATH_SITE.$link;
header("Content-Type: application/octet-stream");
$filename = $getfile.'.pdf';
header("Content-Disposition: attachment; filename=".urlencode($filename));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
JFactory::getApplication()->close();
}
Credits goes to Ashlin rejo.

Webforms in excel instead of e-mail

A client of mine asked me if i can find a solution for this problem.
His website (still a WIP) http://welkommagazine.nl/luuk/ has a form. The form obviously uses a sendmail script to send the form to e-mail. From thereon he manually copy/pastes all the submissions to excel.
What he wants is that the forms online automaticcaly are added to an excel document to save him a lot of work.
Now i am not a programmer, but a designer.. I think this can be done, but i have absolutely no clue how. I googled alot for it and the only thing i found was a dreamweaverplugin.
Is there a way to do this, if so, how?
Not a programmer's response, but...
I think an easy solution is to use Google docs. You can set-up a Google Spreadsheet and associate a form to it. Whenever a user fills the form , his data is added to the spreadsheet.
Your client may download that anytime.
There are some other providers on the market, some free, some not. E.g: wufoo.com
Found the answer myself. I wrote a PHP code snippet which actually stores the fields comma seperated in a CSV file and sends an email to a desired adress with the filled in fields.
if(isset($_POST['Submit'])){
$pakket = $_POST['pakket'];
$extragidsen = $_POST['extragidsen'];
$naambedrijf = $_POST['naambedrijf'];
$err = '';
if(trim($pakket)==''){
$err .= '-Please enter a name';
}
if(empty($extragidsen)){
$err .= '-Please enter an email address';
}
if(strlen($naambedrijf)==0){
$err .= '-Please enter a comment';
}
if($err!=''){
echo $err;
}
else{
$filename = 'file.csv';
$somecontent = $pakket . ',' . $extragidsen . ',' . $naambedrijf . "\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
//--------------------------Set these paramaters--------------------------
// Subject of email sent to you.
$subject = 'Inschrijving welkom';
// Your email address. This is where the form information will be sent.
$emailadd = 'luuk#luukratief.com';
// Where to redirect after form is processed.
$url = 'http://www.google.com';
// Makes all fields required. If set to '1' no field can not be empty. If set to '0' any or all fields can be empty.
$req = '0';
// --------------------------Do not edit below this line--------------------------
$text = "Results from form:\n\n";
$space = ' ';
$line = '
';
foreach ($_POST as $key => $value)
{
if ($req == '1')
{
if ($value == '')
{echo "$key is empty";die;}
}
$j = strlen($key);
if ($j >= 20)
{echo "Name of form element $key cannot be longer than 20 characters";die;}
$j = 20 - $j;
for ($i = 1; $i ';
fclose($handle);
} else {
echo "The file $filename is not writable";
}
}
}
Maybe the code aint that clean as it can be, but eh it works.
Feel free to clean up the code if you want to :)
I guessed I would answer this myself for the community...
BTW u need to set "write" rights to "file.csv"
cheers

Resources