I'm using this example in order to write to Excel from my SQL DB. Most of my data is in cyrilllic, so i am using utf8_unicode_ci(can be seen in code) encoding.
The issue is as follows: module writes into file, but its contents are unreadable due to some mistake. Or maybe it's just Excel '03(i know it's old, yes) i am using? Could anyone help me with this?
<?php
//$host='localhost'; $user='me'; $pass='mypassword'; $DataBase='mydatabase';//define the correct values
require 'connection_data.php';
// open the connexion to the databases server
$Link = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE) or die('Can\'t connect !');
$Link->set_charset('utf8_unicode_ci');//if not by default
//your request
$request='SELECT * FROM Reports';
$result= $Link->query($request);//get the result (ressource)
/** Include PHPExcel */
require_once 'PHPExcel.php';//change if necessary
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$F = $objPHPExcel->getActiveSheet();
$Line=1;
while($row = $result->fetch_assoc()){//extract each record
$F->setCellValue('A'.$Line, $row['Rep_ID']);
$F->setCellValue('B'.$Line, $row['TownName']);
$F->setCellValue('C'.$Line, $row['ShopAdress']);
$F->setCellValue('D'.$Line, $row['ShopName']);
$F->setCellValue('E'.$Line, $row['ProductName']);
$F->setCellValue('F'.$Line, $row['ProductPrice']);
$F->setCellValue('G'.$Line, $row['AddDate']);
$F->setCellValue('C'.$Line, $row['UserName']);//write in the sheet
++$Line;
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="report.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
?>
Related
I am using HTML code in a variable and I do not know how can I pass to generate Excel using PHPExcel.
I am able to generate Excel with load HTML file but if I want use HTML in a variable then I am confused. Please give me an idea on how to implement this.
My sample code is below.
<?php
require_once 'PHPExcel.php';
require_once 'PHPExcel/IOFactory.php';
$objPHPExcel = new PHPExcel();
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="name_of_file.xls"');
header('Cache-Control: max-age=0');
$html ='<table><tr><td><font color="blue">Hello</font></td><td><font style="color: blue;">Rest</font></td></tr><tr><td><font style="color: green;">Next</font></td><td><font style="color: Yellow;">Back</font></td></tr></table>';
$wizard = new PHPExcel_Helper_HTML;
$richText = $wizard->buildTextRun($html);
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', $richText);
$objPHPExcel->getActiveSheet()->setTitle('Sheet 1');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output', 'w');
?>
When I am using it in variable then its showing all in column vise but I want that all should come new row vise.
I need to open a existing xlsx file, that contains text boxes (those created with the predefined option like circles, squares, etc), and I need to write just behind this objects (they are transparent).
The code bellow does everything fine, except that downloads the new file without the boxes.
if(file_exists("app/file.xlsx")){
$objTpl = PHPExcel_IOFactory::load("app/file.xlsx");
$objTpl->setActiveSheetIndex(1);
$objTpl->getActiveSheet()->setCellValue('A1', 'x');
$objTpl->getActiveSheet()->setCellValue('A2', 'y');
$objTpl->getActiveSheet()->setCellValue('A3', 'z');
$filename = 'new_file.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objTpl, 'Excel2007');
ob_end_clean();
$ret = $objWriter->save('php://output');
exit;
}
you can probably do this via the COM dotnet php module
simply open the xlsx file:
$excel = new COM("Excel.Application") or die ("Could not initialise Object.");
$excel->Visible = 1;
$excel->DisplayAlerts = 0;
$Workbook = $excel->Workbooks->Open($file) or die("ERROR: Unable to open " . $file . "!\r\n");
$Worksheet = $Workbook->ActiveSheet;
and from here on out alter your file and then use the saveas function. its all +- well documented in the developers doc from microsoft:
https://msdn.microsoft.com/EN-US/library/office/ff198122.aspx
Hi everyone I have created a program to export MySQL data to excel but at some point I am getting the error the time I am trying to open the excel file.
The error: The file you are trying to open is in a different format,than specified by the file extension.Verify that the file is not corrupt and is from the trusted source before opening the file.Do you want to open the file now?
When I click yes i get the some funny characters on that excel file.
Here is my code:
include 'setup.php';
_connectsurvey(); //Database
require_once 'PHPExcel.php';
$objPHPExcel = new PHPExcel();
$query = "SELECT * FROM questionanswer";
$result = mysql_query($query) or die(mysql_error());
$objPHPExcel = new PHPExcel();
$rowCount = 1;
while($row = mysql_fetch_array($result)){
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['gender']);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['city']);
$rowCount++;
pr($objPHPExcel);
}
header('Content-Type: application/vnd.openxmlformats- officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="survey.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
Near the bottom when you name the file use file extension .xlsx it is the proper file extension for openxml based documents from office 2007 should fix your issue.
header('Content-Disposition: attachment;filename="survey.xlsx"');
If you absolutely need to use xls change the output type to Excel2003 but then you need to change the content type header to match that as well.
The problem was solved: For other users that may have this problem - notice the encoding of the PHP file. If you use PHPExcel it must be ANSII encoding and not UTF8, otherwise the EXCEL will be downloaded corruptly. The Headers that were added (answer 1) solved the problem after i changed the encoding of the file itself.
I am using PHPExcel in order to create an EXCEL from a table in MYSQL DB, so the user can download it to his computer.
The code bellow creates a correct Excel file but the problem is that it is downloaded to my server. I read in PHPExcel manual that i need to add headers:
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$name.'.xls"');
header('Cache-Control: max-age=0');
header('Cache-Control: max-age=1');
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, 'Excel5');
$objWriter->save('php://output');
But if i do that, the downloaded file is:
1. Has some jibrish inside
2. Says that Excel needs to fix it because the file is not good.
The problem is that this file is saved as UTF8 and if i encode it as ANSI then it is working properly but of course it is a manual change and i need a working properly excel to reach the users.
What is the bug?
My code that works (but download the file to the server):
<?php
include 'connection.php';
include 'checkUser.php';
//Getting all the needed information from the DB
$task_id=$_GET['id'];
$query2 = "SELECT * FROM projects WHERE ProjectID=$task_id";
$data2 = mysqli_query($con, $query2);
$row = mysqli_fetch_array($data2);
$project_type = $row['ProjectType'];
$project_name = $row['ProjectName'];
switch ($project_type){
case 2: $NumberOfRows=22; $project = "slivedetails"; break;
case 3: $NumberOfRows=30; $project = "plivedetails"; break;
default: $NumberOfRows=0; $project = "none";
}
//column names
if ($project="slivedetails"){
$ColumnNames = mysqli_query($con,"SHOW COLUMNS FROM slivedetails") or die("mysql error");
}
else if ($project="plivedetails"){
$ColumnNames = mysqli_query($con, "SHOW COLUMNS FROM plivedetails") or die("mysql error");
}
$query = "SELECT * FROM $project WHERE TaskID=$task_id";
$data = mysqli_query($con, $query);
$num_rows = mysqli_num_rows($data);
/** Include PHPExcel */
require_once 'PHPExcel_1.7.9_doc/Classes/PHPExcel.php';
require_once 'PHPExcel_1.7.9_doc/Classes/PHPExcel/IOFactory.php';
// create new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel = new PHPExcel();
// writer already created the first sheet for us, let's get it
$objSheet = $objPHPExcel->getActiveSheet();
// rename the sheet
$objSheet->setTitle('Task Results');
// let's bold and size the header font and write the header
// as you can see, we can specify a range of cells, like here: cells from A1 to A4
$objSheet->getStyle('A1:AD1')->getFont()->setBold(true)->setSize(12);
$char = 65;
// write header]
for ($i=1;$i<=$NumberOfRows;$i++){
$col_name = mysqli_fetch_array($ColumnNames);
$objSheet->getCell(chr($char).'1')->setValue($col_name['Field']);
$char++;
}
// Now we need to get the data from the DB. While we have a row in the result:
$rowIterator=2; //our row number. We begin from 2 because the first one is the title.
while ($RowInfo = mysqli_fetch_array($data)){
//We will fill the information based on the amount of columns:
$char = 65; //we set the first char as column A
for ($i=0;$i<$NumberOfRows;$i++){
$objSheet->getCell(chr($char).$rowIterator)->setValue($RowInfo[$i]);
$char++;
}
$rowIterator++;
}
// autosize the columns
$char = 65;
for ($i=1;$i<=$NumberOfRows;$i++){
$objSheet->getColumnDimension(chr($char))->setAutoSize(true);
$char++;
}
// create the writer
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
$objWriter->save('results.xlsx');
?>
Remove the following inclusion:
require_once 'PHPExcel_1.7.9_doc/Classes/PHPExcel/IOFactory.php';
You declared the object twice. Remove one of them:
// create new PHPExcel object
$objPHPExcel = new PHPExcel();
Insert the following headers just before creating the Writer:
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment; filename=\"results.xlsx\"");
header("Cache-Control: max-age=0");
Instead of the following (which actually saves the file in the server):
$objWriter->save('results.xlsx');
Insert the following (which will create the downloadable file):
$objWriter->save("php://output");
This should solve the gibberish text. If you still get such text, insert the following code before the last line ($objWriter->save("php://output");):
ob_clean();
This worked for me. Hope it helps.
This should work, try to modify your code like this:
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=my_excel_filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
flush();
require_once 'PHPExcel.php';
$objPHPExcel = new PHPExcel();
// here fill data to your Excel sheet
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
Alex, I had the same problem. I did all of them but again result was the same. I just changed
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
to
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
and changed all .xlsx to .xls.
Hope It will help.
Download PHPExcel-1.8(from github) and replace it with the old PHPExcel.
Rename PHPExcel-1.8 to PHPExcel. In my code I have included require '../library/excel/PHPExcel.php';
I deleted all contents from this file (PHPExcel.php) and added only one line of code
require 'PHPExcel/Classes/PHPExcel.php';
(Note: I uploaded PHPExcel in the folder library/excel)
Works perfectly
I am using PHPExcel in my project to generate a xls file of data coming from the database. I have downloaded the library of PHPExcel and using it in my PHP class as give below :
Class name : A.class.php
Path : inside a folder named "inc";
PHPExcel Lib folder : inside "inc" and relative to A.class.php
class A{
// code stuff
public function phpexcelgenerate()
{
require_once 'PHPExcel_1.7.9_doc/Classes/PHPExcel.php';
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="sam.xlsx"');
header('Cache-Control: max-age=0');
$objPHPExcel = new PHPExcel;
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', "12");
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
// This line will force the file to download
$writer->save();
}
// code stuff
}
This code is generating a xls file but that file is fully empty. I am thinking that I have included the files of PHPExcel in a wrong way in PHP classes. Could anyone tell me where I am doing wrong OR an example how can I do the same ?
You need to pass a filename to the save() method. Then read the contents of that files and echo to the browser.
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$writer->save("excel.xls");
readfile("excel.xls");
first of all you need to read the file:
// Read the file
$objReader = PHPExcel_IOFactory::createReader(Excel5);
$objPHPExcel = $objReader->load($fileName);
now get the data from db:
//get data
$details = $this->main_model->get_details()->row();
then assign the data to correct cells:
$objPHPExcel->getActiveSheet()->setCellValue('A'.$row, $i);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$row, $rec->eType);
at the end write the new file:
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
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//force user to download the Excel file without writing it to server's HD
$objWriter->save('php://output');