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
Related
So I have this code:
$datas .= '"' . implode('", "', $body["id"].",".$body["prefecture_id"].",".$body["industry_id"].",".$body["offset"].",".$body["name"].",".$email . ",".$body["tel"].",".$body["fax"].",".$body["address"].",".$body["address_coordinate"].",".$body["url"].",".$body["image_url"].",".$body["flexible_1"].",".$body["flexible_2"].",".$body["flexible_3"].",".$body["flexible_4"].",".$body["flexible_5"].",".$body["flexible_6"].",".$body["flexible_7"].",".$body["flexible_8"].",".$body["flexible_9"].",".$body["flexible_10"].",".$body["sequence"].",".$body["del_flg"].",".$body["create_date"].",".$body["create_user"].",".$body["update_date"].",".$body["update_user"]).'"'."\r\n";
I want it to look like this:
"KN01001","01","4","500","Starbuck's","admin#starbucks.com","09-232-821","09-232-822","Upper G/F SM, Juan Luna Extension"
Problem is address has comma, so this would separate it.
I really could not construct it right. Please help
this code is from a CSV convert function. In the CSV file each column is separated by a comma.
But my problem is that I have several columns that contains also comma. I would like that those commas in the columns remain as it is.
Instead of rolling your own CSV encoding function it might be better to use the built in fputcsv().
$out = fopen("php://memory", "w");
foreach($something as $body) {
fputcsv($out, $body);
}
rewind($out);
$data = stream_get_contents($out);
You'll need to adapt the code to order the columns if you want but that's the basic method (Don't forget to close $out either).
To save holding the entire CSV in memory (if this was a file download/export mechanism) you could open php://output instead and write/flush directly to the web-server/browser.
To answer your question directly implode() takes an array as a second argument but you've given it a string so change it to this (and add all the fields):
$datas .= '"' . implode('", "', [$body["id"], $body["prefecture_id"], $body["industry_id"], $body["offset"], ...]) . "\"\r\n";
can you use fgetcsv() instead of implode? This would handle the
$fileHandle = fopen("filename.csv", "r");
while (($row = fgetcsv($fileHandle, 0, ",")) !== FALSE) {
var_dump($row);
//$row is an array of all the columns in the csv regardless of commas in the dat
}
Otherwise if you must use implode, is the data that has a comma enclosed in speech marks: "some date, with a comma". If so you could use a regex to ignore the commas within the speechmarks. I can't see your data so its hard to say.
I'm trying to input some data into a csv file and it works nicely, but if I try to add the header of the table of data Excel won't let me open the file, because "the file format and extension of file.csv don't match. the file could be corrupted or unsafe".
Here's the code:
//crate headers
$headers[] = "ID";
$headers[] = "Name";
$headers[] = "Ref";
$headers[] = "Quantity";
// crete and open file
$csvName = "file.csv";
$fileHandle = fopen($csvName, 'w') or die('Can\'t create .csv file, try again later.');
//Add the headers, if I take this line out the excel allows me to open the file
fputcsv($fileHandle,$headers,";");
//Add the data
for($i = 0; $i < count($info); ++$i) {
fputcsv($fileHandle,$info[$i],";");
}
//close file
fclose($fileHandle);
EDIT:
Here are the first lines of my csv open with notepad:
ID;Name;Ref;Quantity
2;"Blouse - Color : White, Size : M";demo_2;6
3;"Printed Dress - Color : Orange, Size : S";demo_3;4
If you're intending to use this to create a CSV file that can be opened normally with Excel, the headers shouldn't need to be wrapped in double quotes (because they don't contain any separator characters), and you should use commas rather than semicolons for the separators. However, if you make those changes, you'll still get the same error message when you try to open the resulting file with Excel. Surprisingly, this is because your headers start with 'ID'.
If you can use a different name for that first column header, it could simplify things a bit.
$headers = ["ItemID", "Name", "Ref", "Quantity"];
$csvName = "file.csv";
$fileHandle = fopen($csvName, 'w') or die('Can\'t create .csv file, try again later.');
//Add the headers
fputcsv($fileHandle, $headers);
//Add the data
foreach ($info as $item) {
fputcsv($fileHandle, $item);
}
//close file
fclose($fileHandle);
This should create a .csv file that will open in Excel with no errors.
Try to change your headers to this:
$headers[] = '"ID"';
$headers[] = '"Name"';
$headers[] = '"Ref"';
$headers[] = '"Quantity"';
This will wrap the strings in double quotes, which should fix the syntax issues you are experiencing.
Excel is picky. PHP by default uses commas, which is actually what you want to use for Excel. Semicolons will often work but are not the default - remember, CSV stands for Comma Separated Values. The second problem is specific to Excel. Even though it handles strings without quotes just fine in the data section, for some reason it doesn't work well on the header line. I don't see an option in fputcsv to force quotes, so you need to hardcode them. Something like:
// create and open file
$csvName = "file.csv";
$fileHandle = fopen($csvName, 'w') or die("Can't create .csv file, try again later.");
//Add the headers - note that \r\n or \n is OS dependent
fwrite($fileHandle,'"ID","Name","Ref","Quantity"' . "\r\n");
//Add the data
for ($i = 0; $i < count($info); ++$i) {
fputcsv($fileHandle,$info[$i]);
}
//close file
fclose($fileHandle);
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);
Am trying to read excel file with PHPExcel library
https://github.com/PHPOffice/PHPExcel
however when i read row then am not able to get comments on field and strikes on text also missing .
my code is
include 'PHPExcel/IOFactory.php';
$ftype = 'Excel2007';
$fname = 'data.xlsx';
$objexcel = PHPExcel_IOFactory::load($fname);
$sdata = $objexcel->getActiveSheet()->toArray(null,true,true,true);
foreach ($sdata as $k=>$d) {
print_r($d); // output
}
so it output comments and strikes which are in data.xlsx file are missing .
any idea how to display and check if row have comments and strikes through text
I use the following code to get data from a form and save it as csv.
$cvsData = $name . "," . $address . "\n";
$fp = fopen("file.csv", "a");
if ($fp) {
fwrite($fp, $cvsData); // Write information to the file
fclose($fp); // Close the file
}
When someone enters a comma or line break in address field it breaks the formatting. So how can i escape it so that the whole address stays in the same field ?
Put each data item inside quotation marks. A pair of quotation marks inside a quoted value signifies a single quotation mark. e.g.
"Daniel Norton","Congress Ave.
Austin (""Keeping it weird""), TX"
Referring to your example:
$data = str_replace('"','""',$data);
$address = str_replace('"','""',$address);
$cvsData = "\"$data\",\"$address\"\n";
Better still, just use the PHP function fputcsv.
fputcsv($fp,array($data,$address));
CSV is totally dependent on the software used to read it.
Have a look at http://www.csvreader.com/csv_format.php for some details on how certain programs expect CSV data.
I have created a CSV class that can handle most of these situations. You might want to have a look at it.
https://gist.github.com/1786683
And to answer your question, using that class you could
$csv = CSV::newExcel();
$cvsData = $csv->row($name, $address);
// etc...