I have made a script using PHPExcel to convert .xls files to .csv files.
The .xls file has date formatting in it, and when converted to .csv the date fields has a high number increasing 1 for every day:
So how do I fix this? I want it to say it like this: 10/Jun or 15/Apr.
My code:
$count = 0;
foreach($html->find('section#content_main a') as $e) {
echo "<h3>" . $e->href . "</h3>";
$link = $e->href;
echo "<p>" . $array[$count] . "</p>";
$file = $array[$count] . ".xls";
file_put_contents($file, fopen($link, 'r'));
if(file_exists($array[$count] . ".csv") == 0){
$fileType = PHPExcel_IOFactory::identify($file);
$objReader = PHPExcel_IOFactory::createReader($fileType);
$objReader->setReadDataOnly(false);
for($i = 0; $i < (count($letters) * 2); $i++){
if(i < count($letters)){
}else{
}
}
$objPHPExcel = $objReader->load($file);
$objPHPExcel->getActiveSheet()->getStyle('B2')->getNumberFormat()
->setFormatCode('d-mmm');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save($array[$count] . ".csv");
$count = $count + 1;
echo "<p>File dosen't exist!</p>";
}else{
echo "<p>File do exist!</p>";
}
}
Thanks for the support on my first post.
I don't know what did the trick but i might think that it was this piece of code:
$objPHPExcel->getActiveSheet()->getStyle('B2:B6')->getNumberFormat()
->setFormatCode('d-mmm');
Related
I have created php coding to generate excel file. data are grab from SQL tables but the result are displayed with the HTML tags to the csv file. please see the attached image file which shows the output of below coding.
//genarate report
$out = '';
$filename_prefix = 'showroom_report';
$filename = $filename_prefix."_".$fromDate."-".$toDate;
$pay_array = array();
$showroom_array = array();
$location_id_array = array();
$pay_sql = "SELECT abans_crm.pay_mode.pay_mode,
Count(abans_crm.customers.purchase_type) AS mode_count,
abans_crm.customers.location_id
FROM
abans_crm.customers
INNER JOIN abans_crm.pay_mode ON abans_crm.customers.purchase_type = abans_crm.pay_mode.mode_id
WHERE
DATE(
abans_crm.customers.purchase_date
) >= '$fromDate'
AND DATE(
abans_crm.customers.purchase_date
) <= '$toDate'
GROUP BY
abans_crm.pay_mode.pay_mode";
$pay_result = mysql_query($pay_sql) or die(mysql_error());
if (mysql_num_rows($pay_result) > 0) {
while($row = mysql_fetch_assoc($pay_result)) {
array_push($pay_array, $row);
array_push($location_id_array, $row['location_id']);
}
}
$location_id_unique = array_unique($location_id_array);
$location_id_result = implode(", ", $location_id_unique);
//load showroom names
$showroom_sql = "SELECT
sh_sso.showrooms.showroom_id,
sh_sso.showrooms.showroom_name
FROM
sh_sso.showrooms
WHERE
sh_sso.showrooms.showroom_id IN ($location_id_result)";
$showroom_result = mysql_query($showroom_sql) or die(mysql_error());
while($row = mysql_fetch_assoc($showroom_result)){
array_push($showroom_array, $row);
}
echo "<table border=1 >\n";
echo "<thead><tr class=\"tableizer-firstrow\"><td colspan=6>Enquiries Report - $fromDate-to-$toDate</td></tr></thead><tbody>\n";
echo " <tr><td> </td><td> </td><td> </td><td> </td><td> </td><td> </td></tr>\n";
echo " <tr><td>SHOWROOM</td><td colspan=4>PAYMENT METHOD</td><td rowspan=2>Total</td></tr>\n";
echo " <tr>"
. "<td> </td>"
. "<td>CASH</td>"
. "<td>CREDIT CARD</td>"
. "<td>HIRE PURCHASE</td>"
. "<td>LEASE</td>"
. "</tr>\n";
$cash_val = 0;
$credit_val = 0;
$hire_val = 0;
$lease_val = 0;
$row_total = 0;
for ($i=0; $i < count($showroom_array); $i++) {
$cash_val = searchArray($pay_array, $showroom_array[$i]['showroom_id'], 'Cash');
$credit_val = searchArray($pay_array, $showroom_array[$i]['showroom_id'], 'Credit Card');
$hire_val = searchArray($pay_array, $showroom_array[$i]['showroom_id'], 'Hire Purchase');
$lease_val = searchArray($pay_array, $showroom_array[$i]['showroom_id'], 'Lease');
include_once("../../../includes/sh_cms_functions.php");
$row_total = $row_total + $cash_val;
$row_total = $row_total + $credit_val;
$row_total = $row_total + $hire_val;
$row_total = $row_total + $lease_val;
echo "<tr>"
. "<td>".$showroom_array[$i]['showroom_name']."</td>"
. "<td>".$cash_val."</td>"
. "<td>".$credit_val."</td>"
. "<td>".$hire_val."</td>"
. "<td>".$lease_val."</td>"
. "<td>".$row_total."</td>"
. "</tr>\n";
$row_total = 0;
}
echo "</tbody></table>\n";
//Generate the CSV file header
header("Content-type: application/vnd.ms-excel");
header("Content-Encoding: UTF-8");
header("Content-type: text/csv; charset=UTF-8");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
echo "\xEF\xBB\xBF"; // UTF-8 BOM
//Print the contents of out to the generated file.
print $out;
//Exit the script
exit;
mysql_close();
}
above coding will generate CSV file.
You have HTML in the output, just simply remove it.
I have this code that I use to read Excel 2007 file.
<?php
function load_table(){
require_once('Classes/PHPExcel.php');
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(false);
$objPHPExcel = $objReader->load("SampleData.xlsx");
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow(); // e.g. 10
$highestColumn = $objWorksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
echo '<table class="table">' . "\n";
for ($row = 1; $row <= $highestRow; ++$row) {
echo '<tr>' . "\n";
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
echo '<td>';
$first = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
if($first[0] == '='){
echo $objWorksheet->getCellByColumnAndRow($col, $row)->getCalculatedValue();
}
else
echo $first;
echo '</td>' . "\n";
}
echo '</tr>' . "\n";
}
echo '</table>' . "\n";
}
?>
But I need to read an Excel 2003 file. When I change the code I get error saying that:
Fatal error: Class 'PHPExcel_Reader_Excel2003' not found in ...
Change code:
$objReader = PHPExcel_IOFactory::createReader('Excel2003');
I think you should use
PHPExcel_IOFactory::createReader('Excel5');
or
PHPExcel_IOFactory::createReader('Excel2003XML');
instead of
PHPExcel_IOFactory::createReader('Excel2007');
It's depends your xls file. You can read more details here PHPExcel Docs.
$inputFileType = PHPExcel_IOFactory::identify($inputFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
Make phpexcel identify what type of your file.
Grid lines are not showing up .Below is my code.Please Help.
<?php
require_once '../Classes/PHPExcel.php';
$inputFileName = 'current.xlsx';
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
$objWorksheet = $objPHPExcel->getActiveSheet();
$objPHPExcel->getActiveSheet()->setShowGridlines(true);
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
echo '<div id="xl">' . "\n";
echo '<table>' . "\n";
for ($row = 1; $row <= 2; ++$row) {
echo '<tr>' . "\n";
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
}
echo '</tr>' . "\n";
}
echo '</table>' . "\n";
echo '</div>' . "\n";
?>
I got it displayed as such.Below is my code.
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter->save('php://output');
I use php in order to save all informations concerning my user (where do they navigated and at which time).
So I use the following code for saving informations:
<?php
function iif($condition, $true, $false ) {
return ($condition ? $true : $false);
}
$ipaddress = $_SESSION['login'];
$page = "http://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}";
$page .= iif(!empty($_SERVER['QUERY_STRING']), "?{$_SERVER['QUERY_STRING']}", "");
$referrer = $monUrl = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$datetime = mktime();
$useragent = $_SERVER['HTTP_USER_AGENT'];
$remotehost = #getHostByAddr($ipaddress);
// Create log line
$logline = $ipaddress . '|' . $referrer . '|' . $datetime . '|' . $useragent . '|' . $remotehost . '|' . $page . "\n";
// Write to log file:
$logfile = 'logfile.txt';
$path='log/'.$_SESSION['login'].'/'.$logfile;
if(!file_exists($path)) {
mkdir('log');
mkdir('log/'.$_SESSION['login']);
$f = fopen('log/'.$_SESSION['login'].'/'.$logfile, "x+");
// fermeture
fclose($f);
}
// Open the log file in "Append" mode
if (!$handle = fopen($path, 'a+')) {
die("Failed to open log file");
}
// Write $logline to our logfile.
if (fwrite($handle, $logline) === FALSE) {
die("Failed to write to log file");
}
fclose($handle);
?>
And I use the following code below to display it:
<?php
$path= 'log/'.$data['login'].'/logfile.txt';
$logfile = $path;
if (file_exists($logfile)) {
$handle = fopen($logfile, "r");
$log = fread($handle, filesize($logfile));
fclose($handle);
} else {
die ("Le fichier de Log n'existe pas!");
}
// Seperate each logline
$log = explode("\n", trim($log));
//After that it may be useful to get each part of each logline in a separate variable. This can be done //by looping through each logline, and using explode again:
// Seperate each part in each logline
for ($i = 0; $i < count($log); $i++) {
$log[$i] = trim($log[$i]);
$log[$i] = explode('|', $log[$i]);
}
// Show a table of the logfile
echo '<table id="box-table-a">';
echo '<th scope="col">Agent</th>';
echo '<th scope="col">Referrer</th>';
echo '<th scope="col">Date</th>';
echo '<th scope="col">Useragent</th>';
echo '<th scope="col">Remote Host</th>';
foreach ($log as $logline) {
echo '<tr>';
echo '<td><a href="index.php?p=voir_fiche_employee&id='.$_GET['id'].'"/>' . $logline['0'] . '</a></td>';
echo '<td><a href="'.urldecode($logline['1']).'"/>'. urldecode($logline['1']) . '</a></td>';
echo '<td>' . date('d-m-Y h:i:s', $logline['2']) . '</td>';
echo '<td>' . $logline['3'] . '</td>';
echo '<td>' . $logline['4'] . '</td>';
echo '</tr>';
}
echo '</table>';
?>
The trouble I met is that I really do not know how to sort informations from this file.
In fact on the top of the page I have a form in order to choose between the dates. I wsould like to display all informations from this logfile between those dates but I really do not know how to do.
At the beginning I was planning to save all in the databse, but somebody told me that it would have been too much for the databse, so I decided to save all in a txt on the server.
Does anyone know if it is possible to sort informations from txt file?
By default I would like to display informations of the logfile for the date of the day, and If I want I can choose an other dates or an interval of dates.
If possible to store data into a database. It is easy to sort in database. Reading data into a text file is more time consuming and difficult to sort.
I have seen the ZipArchive class in PHP which lets you read zip files. But I'm wondering if there is a way to iterate though its content without extracting the file first
As found as a comment on http://www.php.net/ziparchive:
The following code can be used to get a list of all the file names in
a zip file.
<?php
$za = new ZipArchive();
$za->open('theZip.zip');
for( $i = 0; $i < $za->numFiles; $i++ ){
$stat = $za->statIndex( $i );
print_r( basename( $stat['name'] ) . PHP_EOL );
}
?>
http://www.php.net/manual/en/function.zip-entry-read.php
<?php
$zip = zip_open("test.zip");
if (is_resource($zip))
{
while ($zip_entry = zip_read($zip))
{
echo "<p>";
echo "Name: " . zip_entry_name($zip_entry) . "<br />";
if (zip_entry_open($zip, $zip_entry))
{
echo "File Contents:<br/>";
$contents = zip_entry_read($zip_entry);
echo "$contents<br />";
zip_entry_close($zip_entry);
}
echo "</p>";
}
zip_close($zip);
}
?>
I solved the problem like this.
$zip = new \ZipArchive();
$zip->open(storage_path('app/'.$request->vrfile));
$name = '';
//looped through the zip files and got each index name of the files
//since I only wanted the first name which is the folder name I break the loop
//after updating the variable $name with the index name and that's it
for( $i = 0; $i < $zip->numFiles; $i++ ){
$filename = $zip->getNameIndex($i);
var_dump($filename);
$name = $filename;
if ($i == 1){
break;
}
}
var_dump($name);
Repeated Question. Search before posting.
PHP library that can list contents of zip / rar files
<?php
$rar_file = rar_open('example.rar') or die("Can't open Rar archive");
$entries = rar_list($rar_file);
foreach ($entries as $entry) {
echo 'Filename: ' . $entry->getName() . "\n";
echo 'Packed size: ' . $entry->getPackedSize() . "\n";
echo 'Unpacked size: ' . $entry->getUnpackedSize() . "\n";
$entry->extract('/dir/extract/to/');
}
rar_close($rar_file);
?>