PHPExcel CSV to XLSX - php

I have a problem converting file feom CSV to XLSX format:
Index.php
<?php
if (!isset($_FILES["file"]))
{
?>
<html>
<body>
<h1>Convert CSV to XLSX</h1>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>
<?php
exit;
}
//obtain PHPExcel from http://phpexcel.codeplex.com
require_once('Classes\PHPExcel.php');
require_once('CSVToExcelConverter.php');
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"];
exit;
}
try
{
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename='.'example.xlsx');
CSVToExcelConverter::convert($_FILES['file']['tmp_name'], 'php://output');
} catch(Exception $e) {
echo $e->getMessage();
}
CSVToExcelConverter.php
class CSVToExcelConverter
{
/**
* Read given csv file and write all rows to given xls file
*
* #param string $csv_file Resource path of the csv file
* #param string $xls_file Resource path of the excel file
* #param string $csv_enc Encoding of the csv file, use utf8 if null
* #throws Exception
*/
public static function convert($csv_file, $xls_file, $csv_enc=null) {
//set cache
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
//open csv file
$objReader = new PHPExcel_Reader_CSV();
if ($csv_enc != null)
$objReader->setInputEncoding($csv_enc);
$objPHPExcel = $objReader->load($csv_file);
$in_sheet = $objPHPExcel->getActiveSheet();
//open excel file
$objPHPExcel = new PHPExcel();
$out_sheet = $objPHPExcel->getActiveSheet();
//row index start from 1
$row_index = 0;
foreach ($in_sheet->getRowIterator() as $row) {
$row_index++;
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
//column index start from 0
$column_index = -1;
foreach ($cellIterator as $cell) {
$column_index++;
$out_sheet->setCellValueByColumnAndRow($column_index, $row_index, $cell->getValue());
}
}
//write excel file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save($xls_file);
}
}
CSV File format: CSV file opened with Excel
xlsx file I get after conversion
Basicaly I would like to get output similar to original csv file, but in xmlx format, how to do that?

The "default" separator for reading a CSV file in PHPExcel is a comma (,). Your CSV file is using something other than a comma - perhaps a tab ("\t"), which is also commonly used for such files).
If the values isn't a comma (and we can't tell from an image of the file viewed in MS Excel) then you have to tell PHPExcel explicitly what that separator is before loading.
e.g.
$objReader->setDelimiter("\t");

Related

phpexcel and csv save to zip using CI zip library

i want to export some data with xlsx and csv format. recently i create some function to do it. and my idea is :
1.save the xlsx and the csv in the temp,
2. add it to the zip library
3. download it.
i have tried to make some functions, and the csv is show an output in the zip, but the excel is not show any output. there is no error, but the excel file doesn't saved at the zip file
Here is my function for creating the excel file
public function createExcel($id){
$excel = PHPExcel_IOFactory::load('C:\xampp\htdocs\api-priadi\ContohExcel.xlsx');
$excel->setActiveSheetIndex(0);
$resultExcel = $this->AdminM->getDataExcel($id);
$rows = 3;
foreach ($resultExcel->result() as $rowExcel){
$excel->getActiveSheet()->setCellValueByColumnAndRow(0,$rows,$rowExcel->id);
$excel->getActiveSheet()->setCellValueByColumnAndRow(1,$rows,$rowExcel->name);
$rows++;
}
$objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$this->zip->add_data('excel'.date('').date('Y_M_d_H_i_s').'.xlsx',$objWriter->save('assets/Haha.xlsx'));
}
and here is the function to create the csv file,
public function createCSV($id){
$csv = fopen("php://temp", "rw");
fputcsv($csv, array('Name', 'Email', 'Birthdate'));
$dataCSV = $this->AdminM->getDataCSV($id);
foreach ($dataCSV as $row){
fputcsv($csv, $row);
}
global $fileCSV;
$fileCSV = stream_get_contents($csv,-1,0);
fclose($csv);
$this->zip->add_data('csv'.date('').date('Y_M_d_H_i_s').'.csv',$fileCSV);
}
and here the code to asssembled the function and download it at the same time.
public function download(){
$id = $this->input->post('id');
$this->createCSV($id);
$this->createExcel($id);
$this->zip->download('testing.zip');
}
what i expect is to download the csv and the excel at the same time
Try to save the xls file first, then load it using PHPExcel_IOFactory::load, then pass the loaded xls file as the zip parameter :
public function createExcel($id){
$excel = PHPExcel_IOFactory::load('C:\xampp\htdocs\api-priadi\ContohExcel.xlsx');
$excel->setActiveSheetIndex(0);
$resultExcel = $this->AdminM->getDataExcel($id);
$rows = 3;
foreach ($resultExcel->result() as $rowExcel){
$excel->getActiveSheet()->setCellValueByColumnAndRow(0,$rows,$rowExcel->id);
$excel->getActiveSheet()->setCellValueByColumnAndRow(1,$rows,$rowExcel->name);
$rows++;
}
$xls_name = 'assets/Haha.xlsx';
$objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$objWriter->save($xls_name);
$objPHPExcel = PHPExcel_IOFactory::load($xls_name);
$this->zip->add_data('excel'.date('').date('Y_M_d_H_i_s').'.xlsx', $objPHPExcel);
}

PHP: reading xls with phpexcel

I am having trouble reading the .xls file. Values ​​are read as null and in unknown characters. The file is downloaded from an ftp server and it comes protected
$path = 'doc/20180719-ASK FIDC_EVOLUCAO_COTA.xls';
$inputFileType = PHPExcel_IOFactory::identify($path);
$reader = PHPExcel_IOFactory::createReader($inputFileType);
$reader->setReadDataOnly(true);
$reader->setInputEncoding('ISO-8859-1');
//$reader->setDelimiter("\t");
$excel = $reader->load($path);
var_dump($excel);
echo $inputFileType;
$writer = PHPExcel_IOFactory::createWriter($excel, 'CSV');
$writer->setUseBOM(true);
$writer->save('data.csv');
echo 'File saved to csv format';
The converted file looks like the image:

Clear the excel file after download it to reuse in PHPExcel

I am creating excel file with single worksheet using PHPExcel.
I have managed to do this but the issue came after when I created it ones then it didn't get clear so when I am creating it again the the previous data came along with the new data.
So I am just want to clear the excel file before using it again.
Here is the code:
require_once APPPATH.'third_party/PHPExcel.php';
require_once APPPATH.'third_party/PHPExcel/IOFactory.php';
//Getting Data form database
$bTob_gstdata = $this->reports_model->get_bTob_gstdata($date_from, $date_to);
//Sample Excel File (which is clear already Just contain the structure)
$filename = 'assets/btob_base_excel.xls';
$objPHPExcel = PHPExcel_IOFactory::load($filename);
echo $filetype = PHPExcel_IOFactory::identify($filename);
$excel2 = PHPExcel_IOFactory::createReader($filetype);
$excel2 = $excel2->load('assets/btob_base_excel.xls'); // Empty Sheet
$excel2->setActiveSheetIndex(0);
$t=0;
$total_invoice_count = 0;
$recipients_count = array();
$invoice_count = array();
for($k=5;$k<(count($bTob_gstdata)+5);$k++)
{
//Adding Data in Excel WorkSheet
$excel2->getActiveSheet()
->setCellValue('A'.$k, $bTob_gstdata[$t]["dist_gstin"]);
$t++;
}
$excel2->getActiveSheet()->setCellValue('A3', (count($recipients_count)));
$excel2->getActiveSheet()->setCellValue('B3', (count($invoice_count)));
$excel2->getActiveSheet()->setCellValue('D3', '=SUM(D5:D'.(count($bTob_gstdata)+5).')');
$excel2->getActiveSheet()->setCellValue('J3', '=SUM(J5:J'.(count($bTob_gstdata)+5).')');
$excel2->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($excel2, $filetype);
$objWriter->save('btocl_gst_report.xls'); //Saving the excel file
header("location:".base_url("btob_gst_report.xls")); // Downloading the excel file
I want to clear the created excel file to Reuse

How to disable Multibyte function overloading in PHP for string functions

I got a problem when call the PHPExcel library AutoLoader.php file.
I try to upload the Excel file, then after clicking on the upload button, it saves data into the database. I get an error, as shown in the photo after uploading the file. How can I fix this?
<?php
require('library/Classes/PHPExcel/IOFactory.php');
/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . '../Classes/');
if(isset($_POST['submit'])){
if((isset($_POST['file'])) && !empty($_POST['file']))
{
$file = $_POST['file'];
}
$fileName= $_FILES["file"]["name"];
echo ('fileName +'.$fileName);
//$uploadPath = $_SERVER['DOCUMENT_ROOT'].'/SMS/excel/' ;
$fileTempName= $_FILES["name"]["temp_name"];
//echo ('fileTempName +'.$fileTempName);
$fileExtension= pathinfo($fileName,PATHINFO_EXTENSION);
$allowedtype= array('xlsx','sls','xlsm');
if(!in_array($fileExtension,$allowedtype)){
echo("<br/>Sorry, File type is not allowed. Only Excel file.");
}
else {
echo("Correct File Extension");
try
{
$inputfiletype = PHPExcel_IOFactory::identify($fileName);
$objReader = PHPExcel_IOFactory::createReader($inputfiletype);
$objPHPExcel = $objReader->load($fileName);
echo 'Reading the number of Worksheets in the WorkBook<br />';
/** Use the PHPExcel object's getSheetCount() method to get a count of the number of WorkSheets in the WorkBook */
$sheetCount = $objPHPExcel->getSheetCount();
echo 'There ',(($sheetCount == 1) ? 'is' : 'are'),' ',$sheetCount,' WorkSheet',(($sheetCount == 1) ? '' : 's'),' in the WorkBook<br /><br />';
echo 'Reading the names of Worksheets in the WorkBook<br />';
/** Use the PHPExcel object's getSheetNames() method to get an array listing the names/titles of the WorkSheets in the WorkBook */
$sheetNames = $objPHPExcel->getSheetNames();
foreach($sheetNames as $sheetIndex => $sheetName) {
echo 'WorkSheet #',$sheetIndex,' is named "',$sheetName,'"<br />';
}
}
catch(Exception $e)
{
die('Error loading file "'.pathinfo($fileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
}
}
?>

Upload Excel File Itself to the Database

I was thinking since i can import the data from excel to my database, is it possible to upload the excel file itself and be able to display it in your website?
For client webpage side, use html form <input type="file"> to upload excel file from browser to PHP file.
Example upload-submit.html:
<form action="upload.php">
<input type="file" name="excel-upload" />
<input type="submit" />
</form>
In your PHP upload script you will need to include the PHPExcel library (https://github.com/PHPOffice/PHPExcel) to read and parse the uploaded Excel file. You can read Mark Baker's very good example on how to read from Excel and insert into a database: how to use phpexcel to read data and insert into database?
Example upload.php :
// Include PHPExcel_IOFactory
include 'PHPExcel/IOFactory.php';
// Move the uploaded file from temporary server directory into an 'uploads' directory
$fileName = basename($_FILES["excel-upload"]["name"]);
$uploadedExcelFullPath = __DIR__.'/uploads/'.$fileName;
move_uploaded_file($_FILES['excel-upload']['tmp_name'],$uploadedExcelFullPath);
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($uploadedExcelFullPath);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($uploadedExcelFullPath);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($uploadedExcelFullPath,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// Insert row data array into your database here
// You can also format data into HTML table row format and echo out here
var_dump($rowData);
}

Categories