php excel export text broken new line - php

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.

Related

When exporting from Kartik ExportMenu widget to Excel, lines breaks only show when double click on it

I installed yii2 extension Kartik ExportMenu since I need to export the filtered result of a GridView to MS Excel 2007. One column of the grid contains a related model, separated each related record by line breaks. The problem is that in the generated Excel file, the content shows in one line and the line breaks only appears when double click each cell. I need line breaks to appear all automatically.
I'm not sure if it's a problem about code or Excel configuration. I've tried in Excel for Mac and in Excel for Windows, with same result.
This is the code of that grid column:
[
'label' => 'Pagos',
'value' => function($model) {
$result = '';
$i = 0;
foreach ($model->ingresos as $ingreso) {
if (++$i === count($model->ingresos)) {
$result = $result . $ingreso->fecha . " - " . $ingreso->moneda->simbolo . " " .
$ingreso->monto . " - " . $ingreso->formaPago->name;
} else {
$result = $result . $ingreso->fecha . " - " . $ingreso->moneda->simbolo . " " .
$ingreso->monto . " - " . $ingreso->formaPago->name . "\n";
}
}
if ($result != '')
return $result;
else
return '-';
},
'format' => 'html',
],
I also have tried the line breaks with <br> and \r, with same result, it opens in one line and I have to double click each cell in order to see the line breaks.
Thanks in advance!
Of course now it's not relevant for you, but maybe it will be useful for others. It seems \n is good as separator, nor stripHtml nor format =html options isn't required. It seems the user must choose "Wrap text" option in excel to show the column as required.
Maybe br html tag is also good separator, when Excel break lines if you double click on the cell. User must choose "Wrap text" option on this column too. Maybe someone know the option in kartik module to avoid the user additional interaction...Sorry for my English.

Import CSV file with tab delimited using PHPExcel lib

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);

mysqli export to xls issue

I have troble geting this work and I can't figure it out what is the issue.
I download a xls file, but it doesent opens.
I had a mysql script like this, working, and I tried to convert it into mysqli and probably something is wrong...
Thanks in advance
$sqlExp = "SELECT * FROM table";
$countQryExp = mysqli_query($link, $sqlExp );
$filename = "sampledata.xls"; // File Name
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
$flag = false;
while($row=mysqli_fetch_array($countQryExp,MYSQLI_ASSOC))
{
if(!$flag) {
// display field/column names as first row
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
echo implode("\t", array_values($row)) . "\r\n";
}
There's a lot more to generating an Excel file than giving it a content type of application/vnd.ms-excel. Excel is a very particular format, whereas you're generating a TSV file - tab separated values, and in a pretty breakable manner (what happens if someone puts a \t in one of your site's fields, or a new line?).
If you want to generate real Excel files, you'll want one of the various libraries for doing so. If a CSV/TSV are fine, just export a .csv/.tsv file with proper headers.

PHPExcel setWrapText(true) not working

I have a serious problem with text wrapping via PHPExcel. I have a column, which contains texts in new lines. It does the linebreaks in LibreOffice. In MS Office it is displayed in a single line. In both viewers, it only does the wrap, when I double click into a cell and then click out the cell. I have the following code:
foreach($view->results as $row){
//...
foreach($unserialized as $task){
$value = $field_info['settings']['allowed_values'][$doc['document']];
$current_tasks .= $value . "\n";
}
$active_sheet->setCellValue($letter.$i, $current_tasks);
//...
//end of main foreach loop
$active_sheet->getStyle('L' . $i)->getAlignment()->setWrapText(true);
$i++;
}
//tried this too outside the foreach:
$active_sheet->getStyle('L2:L' . $i)->getAlignment()->setWrapText(true);
They don't seem to be working. Am I doing something wrong? I googled it up and neither of the solutions worked for me.
I only needed to set the height of the rows.
$numtasks = 20;
foreach($unserialized as $task){
$value = $field_info['settings']['allowed_values'][$doc['document']];
$current_tasks .= $value . "\n";
$active_sheet->getRowDimension($i)->setRowHeight($numtasks);
$numtasks += 20; //20 is for 1 cells height in pixels
}

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.

Categories