Import CSV file with tab delimited using PHPExcel lib - php

I'm trying to import CSV file using PHPExcel lib. My CSV file has \t or tab as delimiter.
So when I'm trying to printout the result in my screen, every comma seen as new cell, just like this
But actually I need to export data in one line for each row and separated by quotation-sign (") for each tab delimiter, just like this one
This is my code in Controller for reading and write the data:
$worksheet = $objPHPExcelDetail->getActiveSheet();
foreach ($worksheet->getRowIterator() as $row) {
echo '<pre>';
echo 'Row number: ' . $row->getRowIndex() . "\r\n";
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
echo 'Cell: ' . $cell->getCoordinate() . ' - ' . $cell->getValue() . "\r\n";
}
}
}
How can I read CSV file with \t separator, and set into one line for each row?

It's the code for loading the file that you need to think about.
Look at the methods available to the CSV Reader in the PHPExcel Documentation.... you'll find that there is a setDelimiter() method that allows you to say to use a tab rather than a ,.
$objReader = PHPExcel_IOFactory::createReader('CSV')
->setDelimiter("\t");
$objPHPExcel = $objReader->load($myFileName);

Related

php excel export text broken new line

I have array data set in column row and export excel but if long text added then line broken.
Can you please suggest how to long text wrap?
$heading = false;
if(!empty($records)) {
foreach($records as $row) {
if(!$heading) {
// display field/column names as a first row
echo implode("\t", array_keys($row)) . "\n";
$heading = true;
}
echo implode("\t", array_values($row)) . "\n";
}
}
Instead of:
echo implode("\t", array_keys($row)) . "\n";
use Chr to return ASCII Code 13:
echo implode("\t", array_keys($row)) . chr(13);
or use PHP_EOL:
echo implode("\t", array_keys($row)) . PHP_EOL;
Edit:
Line breaks will only show in Excel for cells that have "Wor Wrap" enabled.
In your output Excel file:
highlight the data that was output by PHP
right-click on the highlighted cell(s)
choose Format Cells
go to Alignment tab
check box Word Wrap.
If that fixes the issue then your data is (correctly) breaking the line, but it's just Excel's word-wrap default that's preventing the line breaks. You can set it programmatically but it would need a different approach in writing to the file. An easier solution is setup the formatting (including Word Wrap) in the file prior to writing to it, like a template.

Search a cell by string in PHPExcel

I want to know if it's possible to get a cell by its name in an xls document, I mean Ii have this info in a excel file:
Normally to get the coordinate of the cell with the value "ASUS"
$objPHPExcel->getActiveSheet()->getCell('B3')->getValue();
my problem is that users send my this excel file, and sometimes the rows are in disorder, e.g the row B3 sometimes appear in a different row like "B6" or "B7" or "B5", how I can get the cell "ASUS" getting by cell name "Modelo"
There is nothing built-in to PHPExcel to do a search, but using the following example, it can do well for your problem.
$foundInCells = array();
$searchTerm = 'ASUS';
foreach ($objPHPExcel->getWorksheetIterator() as $CurrentWorksheet) {
$ws = $CurrentWorksheet->getTitle();
foreach ($CurrentWorksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
foreach ($cellIterator as $cell) {
if ($cell->getValue() == $searchTerm) {
$foundInCells[] = $ws . '!' . $cell->getCoordinate();
}
}
}
}
var_dump($foundInCells);
You'd have to loop through the entire file to find it just like searching a value in a 2D array.
Take a look at this answer

Issue on .csv files on PHPExcel

I have a problem regarding PHPExcel when reading .csv files.
I wanted to get the values from the .csv file, but the problem is the data from a specific row considered as a single cell.
heres my code:
include 'Classes/PHPExcel/IOFactory.php';
$inputFileType = 'CSV';
$inputFileName = $_FILES['file']['tmp_name'];
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$table = "<table border=1><tr><td>first</td><td>middle</td><td>last</td><td>email</td>";
for ($x = 2; $x <= count($sheetData); $x++){
foreach ($sheetData[$x] as $data){
$first = $sheetData[$x]['A'];
$middle = $sheetData[$x]['B'];
$last = $sheetData[$x]['C'];
$email = $sheetData[$x]['D'];
}
$table .= "<tr><td>" . $first ."</td><td>" . $middle . "</td><td>" . $last . "</td><td>" . $email . "</td></tr>";
}
$table .= "</table>";
echo $table;
It is working on .xls and .xlsx files and I get the desired output that I wanted.
This works fine:
$objReader->setDelimiter("\t");
However, when you are not 100% sure if its tab or comma separated there seems to be no way to add BOTH e.g. $objReader->setDelimiter("\t",); which is something that would be required. When you open Excel and go to Import CSV the actual on screen steps allow you to specify multiple delimiters which is something that would be cool.
Is this something you are working on with PHP Office?
On a separate note here are two links that help you using PHP to find out if the file is comma, tab, or pipe separated - quiet a clever solution:
how to find out if csv file fields are tab delimited or comma delimited
How should I detect which delimiter is used in a text file?
This worked for me:
$objReader = new PHPExcel_Reader_CSV();
$objReader->setDelimiter(';');
$objReader->setEnclosure('');
$objReader->setLineEnding("\r\n");
$objReader->setSheetIndex(0);
$objPHPExcel = $objReader->load($myFile);
More info https://docs.typo3.org/typo3cms/extensions/phpexcel_library/1.7.4/manual.html#_Toc237519888
So what is the separator in your file? Is it a comma, a semi-colon, a tab, something else?
PHPExcel doesn't yet have an automagic detect mode, so unless you specify what separators and enclosures to use, it will default to a comma separator, and a double quote (") enclosure. If your file is using tabs, or semi colons, or some other character as a separator instead, then you need to manually tell the CSV reader what character to use, otherwise it will treat the row as a single cell.
There's a whole section of the User documentation for the Readers devoted to explaining these options for CSV files (section 4.6).
Note that I'm targeting logic to "best guess" separator and enclosure values from the file itself at the #phpnw13 hackathon, but until then you need to specify manually if it isn't the defaults

Exporting to csv formatting issue

I'm trying to export some data into a csv file, I've got the data going into the file, this is my code:
*Please excuse me if the code is bad, I've never done anything like this and this was the only way I could get it working.
/* CSV Export - Create Row */
$csv_row_content .= $userdata->id.',';
$csv_row_content .= $userdata->firstname.' '.$userdata->lastname;
$csv_row_content .= ','.$split_date[2].'-'.$split_date[1].'-'.$split_date[0].',';
$csv_row_content .= $sale->name;
if($sale->optionlabel):
$csv_row_content .= ' ('.$sale->optionlabel.')';
endif;
$csv_row_content .= ',';
$csv_row_content .= $sale->status.',';
$csv_row_content .= number_format($sale->unitprice, 2, '.', '');
$csv_row_content .= "\r\n";
$data_array[] = $csv_row_content;
$csv_file = fopen('../wp-content/plugins/data-export/export_doc.csv', 'w');
foreach ($data_array as $single_line)
{
fputcsv($csv_file,split(',',$single_line));
}
fclose($csv_file);
/* Clear Array */
unset($data_array);
$data_array = array();
It's working except I'm having trouble with the quotations marks on certain items
303,"User Name",12-02-2013,"College Sweater (Black)",,"20.00
207","User Name",30-01-2013,"College Sweater (Black)",,"20.00
"
So I'm not sure what the go is with the first and last items, the one quotation mark show up sometimes and not in others.
Notice the odd quotation mark on row id 207 & on the last value for both row.
Also there's a new line begin made on the third row with just a single quote.
Also on some other items the function is splitting the name of the item into two items. eg:
207","User Name",30-01-2013,"College ","Sweater (Black)",,"22.73
So obviously I'm off base here somewhere, if anyone could help me with this, I'm really keen on learning the correct way this kind of thing should be done, checked the php.net docs quite a bit, but a lot of the time I find that resource incredibly overwhelming and this is one such occasion.
If anyone can point me in the right direction on this I'd really appreciate it.
I'd prefer to understand this than just have a copy and paste solution.
Thanks,
Frank
You are manually creating a CSV string and splitting it before using fputcsv to put it back together. Try this instead:
$row = array(
$userdata->id,
$userdata->firstname . ' ' . $userdata->lastname,
$split_date[2] . '-' . $split_date[1] . '-' . $split_date[0],
$sale->name . ($sale->optionlabel ? $sale->optionlabel : ''),
$sale->status,
number_format($sale->unitprice, 2, '.', '')
);
$data[] = $row;
$csv_file = fopen('../wp-content/plugins/data-export/export_doc.csv', 'w');
foreach ($data as $line) {
fputcsv($csv_file, $line);
}
fclose($csv_file);
This creates an array containing all the fields which can be passed to fputcsv which takes care of enclosing and delimiting fields as well as line endings.

XML to CSV = invalid Argument

Hello I have the following xml results that are returned from a remote site
<ResultSet totalResultsAvailable="1">
<Product orderNo="5321" partNo="A2345" truckable="1">
<Manufacturer id="22">WIDGET 4 U</Manufacturer>
<Model id="356">ACME 500</Model>
<Years>95-98</Years>
<ProductType id="23" categoryID="4">Cool Red Widgest</ProductType>
<Material id="6">shiny stuff</Material>
<PartNo>A2345</PartNo>
<Code/>
</Product>
</ResultSet>
I am simply trying to pull the xml results and place in a new csv file with the following code:
but I get and error: Warning:
Invalid argument supplied for foreach() in /home/myServer/public_html/xmlParser2.php on line 14
Here is my code:
<?
echo 'Write XML to CSV';
$basenameLong ='http://thisIsTheURLto.com/myFeed/?key=123456789&mode=getProducts;
$fileNameCSV = 'xmlParseContent.csv';
$feedContent = '';
echo '<br/>Starting......';
$feedContent = file_get_contents($basenameLong);
$fh = fopen($fileNameCSV, 'w+'); //create new CSV file if not exists else append
foreach($feedContent->ResultSet->Product as $product) {
fputcsv($f, get_object_vars($product),',','"');
}
fclose($fh);
?>
I know this code is very elementary but can you help me find the issue. I am a novice and I dont see it.
This line is wrong :
fputcsv($f, get_object_vars($product),',','"');
if you want to put blank values, try doing this :
fputcsv($f, get_object_vars($product),'','','');
Your problem is that you never parse your XML file. Replace file_get_contents with simplexml_load_file and it should work.
Using PHP to convert XML to CSV is fairly easy, at least in the situations I've encountered so far. In my case, it would save me significant work if I could simply convert structured XML data into CSV data. Typically, I want to convert only the data in a particular xpath of the original XML document. The PHP function below will load an XML file and convert the elements in the specified xpath to simple csv data.
function xml2csv ($xmlFile, $xPath) {
// Load the XML file
$xml = simplexml_load_file($xmlFile);
// Jump to the specified xpath
$path = $xml->xpath($xPath);
// Loop through the specified xpath
foreach($path as $item) {
// Loop through the elements in this xpath
foreach($item as $key => $value) {
$csvData .= '"' . trim($value) . '"' . ',';
}
// Trim off the extra comma
$csvData = trim($csvData, ',');
// Add an LF
$csvData .= "\n";
}
// Return the CSV data
return $csvData;
}

Categories