convert an EXCEL file to CSV file in PHP [duplicate] - php

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

Related

Generate .xlsx file using fromArray for a big amount of data

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

Read excel sheet containing merged cells using PHPExcel

I want to read an excel sheet completely and using AJAX send each row to another page for processing. So I have used the following code for converting the excel sheet data into JSON array(Reference PHPExcel example provided in Library):
<?php
error_reporting(E_ALL);
set_time_limit(0);
date_default_timezone_set('Asia/Kolkata');
set_include_path(get_include_path() . PATH_SEPARATOR . 'PHPExcel-1.8/Classes/');
require_once 'PHPExcel/IOFactory.php';
$inputFileType = PHPExcel_IOFactory::identify($fileLocation);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setLoadSheetsOnly("SHEETNAME");
$objPHPExcel = $objReader->load($fileLocation);
$data = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
?>
Here $filelocation is the location of the uploaded file which is to be read for sending the rows individually using AJAX to another page.
I am using $data in javascript as
DataToBeUploaded=<?php echo json_encode($data);?>;
But the excel sheet contains some merged cells so PHPExcel is not able to read the values in these merged cells. Hence values in these cells are read as NULL.
Is there a way where I can use the merged cells' upper left cell value for all of the subsequent cells? (Actually in my case cells are merged vertically only)
Eg.
I have (Assume rows are numbered from 1 and columns from A)
Here PHPExcel reads this as:
data[1][A]='abc'
$data[1][B]='123'
$data[2][A]=''
$data[2][B]='456'
$data[3][A]=''
$data[3][B]='789'
I want the snippet to result in these values:
data[1][A]='abc'
$data[1][B]='123'
$data[2][A]='abc'
$data[2][B]='456'
$data[3][A]='abc'
$data[3][B]='789'
Referring to https://github.com/PHPOffice/PHPExcel/issues/643
I have written the following snippet:
$referenceRow=array();
for ( $row = 2; $row <= $noOfBooks; $row++ ){
for ( $col = 0; $col < 7; $col++ ){
if (!$objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->isInMergeRange() || $objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->isMergeRangeValueCell()) {
// Cell is not merged cell
$data[$row][$col] = $objPHPExcel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->getCalculatedValue();
$referenceRow[$col]=$data[$row][$col];
//This will store the value of cell in $referenceRow so that if the next row is merged then it will use this value for the attribute
} else {
// Cell is part of a merge-range
$data[$row][$col]=$referenceRow[$col];
//The value stored for this column in $referenceRow in one of the previous iterations is the value of the merged cell
}
}
}
This will give the result exactly as required

Read excel data Sheet by sheet using codeigniter and mysql and phpexcel

I am done with basic import to database. I have explained in the following example where I got stuck up ...
For example,
I have an xls file named project.xls and it has 6 sheets. I have populated all 6 sheet names in dropdown. If I select sheet2 and click button, it should import sheet2 data into db and sheet3 so on.
How can I do this ...? please help me...
You can access to differents sheets of a file with PHPExcelReader this way:
$filename = "path/to/filename.xls";
$reader = new Spreadsheet_Excel_Reader(); // Your PHPEXCELREDER Class
$reader->setOutputEncoding('UTF8');
// Read XLS File
$reader->read($filename);
$sheet = 2; // Your sheet
// Then walk trough your wanted sheet:
for ($i = 2; $i <= $reader->sheets[$sheet]['numRows']; $i++) {
// Do something
}

PHPExcel; Issue with Array from MySQL

I'm new to PHPExcel, obviously.. I'm also pretty new to PHP in itself.
The website has multiple levels of authority for viewing/editing.
I've been working on a page for a website that gathers information stored in the SQL database and populates an excel template.
application.php contains all the database connections etc.
Basically, the problem I'm having is when I call on the array to populate cells it shows up as duplicates of the same array value. Not only that, but it crams them all onto the same column.
The Values I would need to populate are:
Part No. Description U/Price Q'ty Total
15666562003 Lamp Assembly $20.00 1 $20.00
Freight 131514 $12.35 1 $12.35
The data would show up like this:
Part No. Description U/Price Q'ty Total
Freight Freight 131514 131514 $12.35 $12.35 1 1 $12.35 $12.35
Any help would be much appreciated!!
<?php
include "./include/application.php";
require './Classes/PHPExcel.php';
error_reporting(E_ALL ^ E_NOTICE);
class CForm extends CApplication
{
function CForm()
{
$this->CApplication();
}
//**********************************************************
function Export($msg = "")
{
if ($_SESSION['aID'] == "" && $_SESSION['mID'] == "237" && $_SESSION['mID'] == "178" && $_SESSION['mID'] == "551")
{
$sWhere = " AND dID = '$_SESSION[mID]'";
}
$sql = "SELECT * FROM dl_warranty_claims
INNER JOIN dealers ON (dID = wDealerID)
WHERE 1 ".$sWhere." AND wID = '$_GET[id]'";
$res = $this->SQL($sql);
if (!($row = $this->FetchArray($res)))
{
print "You do not have access to view this report.";
exit();
}
error_reporting(E_ALL ^ E_NOTICE);
// Read the template file
$inputFileType = 'Excel2007';
$inputFileName = './templates/warrantyclaimtemplate2.xlsx';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
// Adding data to the template
$objPHPExcel->getActiveSheet()->setCellValue('A3', ($row['wDealerName']));
$objPHPExcel->getActiveSheet()->setCellValue('B3', ($row['wID']));
$objPHPExcel->getActiveSheet()->setCellValue('C3', ($row['wCustomerName']));
$objPHPExcel->getActiveSheet()->setCellValue('D3', ($row['wModelName']));
$objPHPExcel->getActiveSheet()->setCellValue('E3', ($row['wChassisSN']));
$objPHPExcel->getActiveSheet()->setCellValue('F3', ($row['wEngineSN']));
$objPHPExcel->getActiveSheet()->setCellValue('G3', ($row['wDateDelivery']));
$objPHPExcel->getActiveSheet()->setCellValue('H3', ($row['wDateFailure']));
$objPHPExcel->getActiveSheet()->setCellValue('I3', ($row['wDateClaim']));
$objPHPExcel->getActiveSheet()->setCellValue('J3', ($row['wOperatingHours']));
$sql = "SELECT * FROM dl_warranty_parts
WHERE wpWarrantyClaimID = '$_GET[id]'";
$res = $this->SQL($sql);
while($rowp = $this->FetchArray($res))
{
$objPHPExcel->getActivesheet()->FromArray($rowp, NULL, 'A4');
}
// Write and save file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
header('Content-Type: application/vnd.openxmlformats- officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="warrantyclaimreport.xlsx"');
$objWriter->save('php://output');
}
}
?>
Your save statement
$objWriter->save('WarrantyClaim.xlsx');
is writing a file called WarrantyClaim.xlsx to disk (in the current working directory of your script).
Yet you have headers aying that you're going to send the output to the browser
Besides sending the correct headers for the filetype that you're writing:
Filetype Writer Content type
.xls Excel5 application/vnd.ms-excel
.xlsx Excel2007 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
saving to php://output will send the file to the browser
You also have a similar issue with your Reader: using the Excel5 Reader to read a .xlsx file when you should be using the Excel2007 Reader
For your latest question (please learn how to ask questions on SO, you don't simply edit a previous question when you have a new question, but should ask a new question)
Your $this->FetchArray() method appears to be returning both enumerated and associative data... I don't know exactly what the arguments are, but there should be some setting that allows you to specify either enumerated or associative, or a method call such as FetchAssoc() that will specifically return only an associative array

PHPexcel CSV master file

I would like to have multiple csv's and add them in a master csv file. It when I add an extra csv file in the array it throws a exception error.
Uncaught exception 'Exception' with message 'Workbook already contains a worksheet named 'Worksheet'. Rename the external sheet first.' in
Please find below my code
include'../Classes/PHPExcel.php';
include'../Classes/PHPExcel/IOFactory.php';
$filenames = array('Sheet1.csv','Sheet2.csv');
$bigExcel = new PHPExcel();
$bigExcel->removeSheetByIndex(0);
$reader = new PHPExcel_Reader_CSV();
foreach ($filenames as $filename) {
$excel = $reader->load($filename);
foreach ($excel->getAllSheets() as $sheet) {
$bigExcel->addExternalSheet($sheet);
}
foreach ($excel->getNamedRanges() as $namedRange) {
$bigExcel->addNamedRange($namedRange);
}
}
$writer = new PHPExcel_Writer_CSV($bigExcel);
$writer->save('2007-write.csv');
The problem is with the following code:
foreach ($excel->getAllSheets() as $sheet) {
$bigExcel->addExternalSheet($sheet);
}
For file 1 you add a sheet called worksheet, and then for file two you try to add a sheet with the same name.
I suggest you check if a sheetname has already been added, and if so you can use "setActiveSheetIndex" to switch to the existing sheet.
Another option is to change the name to worksheet(2) if you find one that already exists.
But since you called it CSV I dont think you can use worksheets. So in the end it should all just go in a single worksheet, so no need to keep adding new workheets. Just create one and add all the data to that one.

Categories