I have the following method to create an Excel file from in PHP starting with a two-dimensional array:
header("Content-Disposition: attachment; filename=ExcelFile.xls");
header("Content-Type: application/vnd.ms-excel");
$Data[] = array('field1', 'field2', 'field3');
$Data[] = array('field1', 'field2', 'field3');
$Data[] = array('field1', 'field2', 'field3');
foreach($Data as $key => $val) {
echo implode("\t", array_values($val)) . "\n";
}
Would it be possible to include a hyperlink to a webpage in this file?
For any kind of useful cell manipulation besides the basic .csv output approach, you might want to consider PHP COM.
Here's a very rough example that borrows heavily from this link just to give you the gist of what it'll look like:
//create instance of excel on the server
$excel = new COM("excel.application") or die("Unable to create excel object");
//add a book and a worksheet and activate the worksheet
$workbook = $excel->Workbooks->Add();
$worksheet=$workbook->Worksheets(1);
$worksheet->activate;
//pick an active cell (here it's A1) and add text plus a hyperlink
$cell=$worksheet->Cells(1,1);
$cell->Activate;
$cell->value = 'your hyperlink text';
//i took this syntax from my native MS VBA, so check syntax
$cell->Hyperlinks.Add.ActiveCell, 'http://yourdomain.com'
//save your doc
$worksheet->SaveAs([[your path]]);
//close everything up and free up resources
$worksheet->Close(false);
$excel->Workbooks->Close();
unset($sheet);
$excel->Quit();
$excel = null;
Results may vary, depending on all the bug reports one reads on this topic.
Related
I need to write in a .xlsx file about 111.100 rows, using fromArray() but I have a strange error
I use phpspreadsheet library
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$columnLetter = 'A';
foreach ($columnNames as $columnName) {
// Allow to access AA column if needed and more
$sheet->setCellValue($columnLetter.'1', $columnName);
$columnLetter++;
}
$i = 2; // Beginning row for active sheet
$columnLetter = 'A';
foreach ($columnValues as $columnValue) {
$sheet->fromArray(array_values($columnValue), NULL, $columnLetter.$i);
$i++;
$columnLetter++;
}
// Create your Office 2007 Excel (XLSX Format)
$writer = new Xlsx($spreadsheet);
// In this case, we want to write the file in the public directory
// e.g /var/www/project/public/my_first_excel_symfony4.xlsx
$excelFilepath = $directory . '/'.$filename.'.xlsx';
// Create the file
$writer->save($excelFilepath);
And I get the exception :
message: "Invalid cell coordinate AAAA18272"
#code: 0
#file: "./vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Cell/Coordinate.php"
Can you help me please ?
Excel pages are limited. The limit is huge but still limited. This is a correct filter so you can't write if there is no space for it.
Anyway you shouldnt use excel pages for such a big amount of data, you can try fragmenting it into smaller pieces, but databases should be the way to manipulate such amount of information
I am using fputcsv for write data. It is working fine. what i need is i need to create another sheet like any name and i need to write data on that. How to do that? Please guide. I am not familiar with this.
This is my code.
$filename = date("Y-m-d").".csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
header("Content-Transfer-Encoding: UTF-8");
$fp = fopen('php://output', 'a');
$yetToaproveFields = array('job_no'=>'Job Number',
'revisioncycle'=> 'Revision Cycle',
'version'=>'Version',
'is_approved'=>'Approved Status'
);
fputcsv($fp, $yetToaproveFields);
$notApproveArr = array();
$notApprovedValues = self::getNotApprovedJobs($_REQUEST);
foreach ($notApprovedValues as $key=>$value) {
if ($value['is_approved'] == 1)
$value['is_approved'] = 'No';
fputcsv($fp, $value);
}
fclose($fp);
CSV doesn't support multiple sheets, it's a simple text file. To use sheets, you should use an Excel extension, such as PHPExcel.
You can't.
CSV is a very simple data file format. It doesn't support spreadsheet features like styling or multiple worksheets. If you want multiple worksheets, then you need to use a spreadsheet file format like BIFF (.xls), OfficeOpenXML (.xlsx) or OASIS (.ods)
This question already has answers here:
How to convert Excel XLS to CSV using PHP
(5 answers)
Closed 7 years ago.
I want to convert Excel files (.xls) into CSV file (.csv) with a script PHP ?
I tried many codes but it didn't work like this one !
No errors appear but it wont work Any idea or any other lines of codes that I can try ?
<?php
echo("it works");
require_once '../batchs/Classes/PHPExcel/IOFactory.php';
$inputFileType = 'Excel5';
$inputFileName = '../public/aixstream/stock.xls';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcelReader = $objReader->load($inputFileName);
$loadedSheetNames = $objPHPExcelReader->getSheetNames();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcelReader, 'CSV');
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
$objWriter->setSheetIndex($sheetIndex);
$objWriter->save($loadedSheetName.'.csv');
}
?>
Thank you
As already stated in this answer, you can use the PHP-ExcelReader function to read the xls file. After that, you may easily convert it into CSV (or any other other format) using the following code, also available here.
Reading the xls file
//You will obviously need to import the function
//by downloading the file from the link above.
$reader=new Spreadsheet_Excel_Reader(); //Instantiate the function
$reader->setUTFEncoder('iconv'); // Set Encoder
$reader->setOutputEncoding('UTF-8'); // Set Output Encoding Type
$reader->read($filename); // Read the xls file
Data Output
/***
* Information about sheets is stored in boundsheets variable.
* This code displays each sheet's name.
***/
foreach ($reader->boundsheets as $k=>$sheet) //Run loop for all sheets in the file
{
echo "\n$k: $sheet";
}
//Now just save the data in the array as csv
/***
* Data of the sheets is stored in sheets variable.
* For every sheet, a two dimensional array holding table is created.
* This code saves all data to CSV file.
***/
foreach($reader->sheets as $k=>$data) // Run loop for all items.
{
echo "\n\n ".$reader->boundsheets[$k]."\n\n"; //Print Title
foreach($data['cells'] as $row) // Loop for all items
{
foreach($row as $cell) // Loop for every cell
{
echo "$cell".","; //Add a comma after each value
}
}
}
//It works! :D
I have troble geting this work and I can't figure it out what is the issue.
I download a xls file, but it doesent opens.
I had a mysql script like this, working, and I tried to convert it into mysqli and probably something is wrong...
Thanks in advance
$sqlExp = "SELECT * FROM table";
$countQryExp = mysqli_query($link, $sqlExp );
$filename = "sampledata.xls"; // File Name
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
while($row=mysqli_fetch_array($countQryExp,MYSQLI_ASSOC))
{
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
echo implode("\t", array_values($row)) . "\r\n";
}
There's a lot more to generating an Excel file than giving it a content type of application/vnd.ms-excel. Excel is a very particular format, whereas you're generating a TSV file - tab separated values, and in a pretty breakable manner (what happens if someone puts a \t in one of your site's fields, or a new line?).
If you want to generate real Excel files, you'll want one of the various libraries for doing so. If a CSV/TSV are fine, just export a .csv/.tsv file with proper headers.
I have array of data like:
$products = array(
array('path/to/image1', 'name1', 'description1'),
array('path/to/image2', 'name2', 'description2'),
array('path/to/image3', 'name3', 'description3'),
...
array('path/to/imageN', 'nameN', 'descriptionN'),
);
With this code I generate *.xlsx table:
foreach($products as $row) {
$c = 0;
foreach ($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($c, $r, $cell);
$c++;
}
$r++;
}
require_once 'Classes/PHPExcel/IOFactory.php';
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('/path/for/save');
And after that I get a table with path, name and descriptions. Please help me, because I can't get table where instead of pathes I will get images.
Setting a cell to contain 'path/to/image1' will do exactly that, set the cell to contain a string value of 'path/to/image1'.
You need to set images very specifically, as explained in the documentation and shown in the examples:
$objDrawing = new PHPExcel_Worksheet_Drawing();
$objDrawing->setName('Image');
$objDrawing->setPath('./path/to/image1.jpg');
$objDrawing->setCoordinates('B2');
$objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
You should also note that MS Excel does not store images in a cell. It stores images overlaying a cell, so the image may cover several cells
EDIT
If you need to convert numeric coordinates such as $row=3 and $col=0 to a cell reference like A3:
$cellReference = PHPExcel_Cell::stringFromColumnIndex($col) . $row;
or
$cellReference = $objPHPExcel->getActiveSheet()
->getCellByColumnAndRow($col, $row)
->getCoordinate();