How to read spreadsheet with no scientific notation? - phpspreadsheet

Im loading a simple CSV file containing some long numbers.
-5605138260238298086
-5605138260238298086
-5605138260238297950
-5605138260238297950
-5605138260238297950
-5605138260238297950
-5604797085080996904
Trying to do a basic load of this CSV results in numbers that are returned as scientific notation like:
-5,60514E+18
How do I avoid getting a printout with scientific notation?
I've tried with the following:
if ( $ext == 'csv' ) {
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Csv");
} else {
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
}
$spreadsheet = $reader->load( $movefile['file'] );
$data = $spreadsheet->getActiveSheet()->toArray();
foreach ( $data as $row_key => $row ) {
foreach ( $row as $cell_key => $cell ) {
if ( $cell )
$file_data[$row_key][$cell_key] = $cell;
}
}

Related

phpspreadsheet read and getting values using header (1st row value)

How can i get all values from excel using 1st row value
It's working for me using this commande $spreadSheetAry[$i][0], but i need it $spreadSheetAry[$i]["Tracking_Number"]
it's possible?
This is code example:
<?php
use Phppot\DataSource;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
require_once 'DataSource.php';
$db = new DataSource();
$conn = $db->getConnection();
require_once ('./vendor/autoload.php');
$allowedFileType = [
'application/vnd.ms-excel',
'text/xls',
'text/xlsx',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
];
$targetPath = 'uploads/test.xlsx';
$Reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$header = ["Tracking_Number", "Referance"];
$spreadSheet = $Reader->load($targetPath);
$excelSheet = $spreadSheet->getActiveSheet();
$spreadSheetAry = $excelSheet->toArray();
$sheetCount = count($spreadSheetAry);
for ($i = 0; $i <= $sheetCount; $i ++) {
$TN = "";
if (isset($spreadSheetAry[$i][0])) {
$TN = mysqli_real_escape_string($conn, $spreadSheetAry[$i][0]);
}
$RF = "";
if (isset($spreadSheetAry[$i][1])) {
$RF = mysqli_real_escape_string($conn, $spreadSheetAry[$i][1]);
}
echo $TN." - ".$RF."<br/>";
}
?>
Excel example:
enter image description here

PhpSpreadsheet Notice: Undefined offset: 4

I have been struggling with finding a way to read excel files in a directory, copy the worksheet called "Division" into a new file, then number the new worksheets increment by one - Division1, Division2, etc...
The following is my code, which I am receiving a warning for undefined index, which is not a big deal, but it only creates a new excel file with only four worksheets, when there should be over 240 worksheets.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
$exportedFiles = scandir('PhpSpreadsheet/Export');
$inputFileNames = [];
$sheetnames = [];
$outfile = 'all-together-now.xlsx';
foreach($exportedFiles as $key=> $value) {
if ($value == '.' || $value == '..') {
} else {
array_push($inputFileNames, 'PhpSpreadsheet/Export/' . $value);
array_push($sheetnames, 'Division');
}
}
$inputFileType = 'Xlsx';
$reader = IOFactory::createReader($inputFileType);
$reader->setLoadSheetsOnly($sheetnames);
$contador = 1;
foreach ($inputFileNames as $book => $inputFileName) {
echo ('$inputFileName: ' . $inputFileName) . '</br>';
$reader = IOFactory::createReader("Xlsx");
$spreadsheet = $reader->load($inputFileName);
$clonedWorksheet = clone $spreadsheet->getSheetByName('Division');
$clonedWorksheet->setTitle('Division' . $contador);
$spreadsheetMain = $reader->load($outfile);
$spreadsheetMain->addSheet($clonedWorksheet);
$writer = IOFactory::createWriter($spreadsheetMain, "Xlsx");
$writer->save($outfile);
$contador++;
}
The following are the warning notices:
Notice: Undefined offset: 4 in
PhpOffice\PhpSpreadsheet\Writer\Xlsx->save( )
PhpOffice\PhpSpreadsheet\Spreadsheet->garbageCollect( )
As usual, thanks in advance
Part of the solution was bumping up the memory and the other was to use addSheet()
The following is the code that works:
ini_set('memory_limit','32768M');
use PhpOffice\PhpSpreadsheet\IOFactory;
require_once 'PhpSpreadsheet/src/Bootstrap.php';
$exportedFiles = scandir('PhpSpreadsheet/Export');
$inputFileNames = [];
$sheetnames = [];
$outfile = 'all-together-now.xlsx';
foreach($exportedFiles as $key=> $value) {
if ($value == '.' || $value == '..') {
} else {
array_push($inputFileNames, 'PhpSpreadsheet/Export/' . $value);
array_push($sheetnames, 'Division');
}
}
$inputFileType = 'Xlsx';
$reader = IOFactory::createReader($inputFileType);
$reader->setLoadSheetsOnly($sheetnames);
$contador = 1;
foreach ($inputFileNames as $book => $inputFileName) {
echo ('$inputFileName: ' . $inputFileName) . '</br>';
$reader = IOFactory::createReader("Xlsx");
$spreadsheet = $reader->load($inputFileName);
$spreadsheet->getSheetByName('Division')->getStyle('Division');
$clonedWorksheet = clone $spreadsheet->getSheetByName('Division');
$clonedWorksheet->setTitle('Division' . $contador);
/* open new file for writing spread sheets to it */
$spreadsheetMain = $reader->load($outfile);
$spreadsheetMain->addSheet($clonedWorksheet);
$writer = IOFactory::createWriter($spreadsheetMain, "Xlsx");
$writer->save($outfile);
$contador++;
}
$spreadsheet->disconnectWorksheets();
echo "The process has completed";
die();
The aforementioned script created an excel workbook with 247 worksheets from the 247 excel files

Can not add a list in document object using iTextSharp

public ActionResult PartTimeFacultyCourseLoadReport()
{
var teacherStatistics = (from t in db.Teachers
join c in db.Courses
on t.Id equals c.TeacherId into cGroup
where t.Status == "Part Time"
orderby t.Designation descending
select new
{
TeacherInfo = t,
CourseInfo = from cg in cGroup
orderby cg.Code ascending
select cg
}).ToList();
List<TeacherStatistics> teacherStatisticses = new List<TeacherStatistics>();
int count = 0;
foreach (var teacherStatistic in teacherStatistics)
{
TeacherStatistics aTeacherStatistics = new TeacherStatistics();
aTeacherStatistics.Name = teacherStatistic.TeacherInfo.Name;
aTeacherStatistics.Designation = teacherStatistic.TeacherInfo.Designation;
aTeacherStatistics.NumberOfCourse = teacherStatistic.TeacherInfo.NumberOfCourse;
count = 0;
foreach (var courseInfo in teacherStatistic.CourseInfo)
{
if (count != 0)
{
aTeacherStatistics.Courses += ", ";
}
aTeacherStatistics.Courses += courseInfo.Code;
aTeacherStatistics.Courses += "(";
aTeacherStatistics.Courses += courseInfo.Section;
aTeacherStatistics.Courses += ")";
count++;
}
teacherStatisticses.Add(aTeacherStatistics);
}
var document = new Document(PageSize.A4, 50, 50, 25, 25);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);
document.Open();
var data = teacherStatisticses.ToList();
document.Add(data);
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=PartTimeFaculty.pdf");
Response.BinaryWrite(output.ToArray());
document.Close();
return View(teacherStatisticses);
}
I want to pass a list named 'teacherStatisticses' through document object for making a PDF. My code doesn't work. It showed me following Error -
Argument 1: cannot convert from 'System.Collections.Generic.List' to 'iTextSharp.text.IElement'
I assume that you are using some version of itextpdf for the PDF generation.
The error is in the line:
document.Add(data);
There is no way to add plain .NET objects into the PDF document. I can not predict the structure of PDF which you`d like to achieve, but the code mentioned above could be written as:
foreach(var teacher in teacherStatistics)
{
var paragraph = new Paragraph(teacher.ToString()); // instead of teacher.ToString() should be some code which translates teacherStatistics projection to the string representation
document.Add(paragraph);
}
//not tested
A lot of useful samples could be found at
http://developers.itextpdf.com/examples
Basic tutorial for the itextpdf:
http://developers.itextpdf.com/content/itext-7-jump-start-tutorial/chapter-1-introducing-basic-building-blocks

Google spreadsheet: Download all the sheets at once

When working with google spreadsheet, how to download all the sheets at once?
I want to use the option:
Comma-separated values
But it only download the current sheet, how to get them all?
For anyone who navigates to this question, trying to download all the tabs in their Google spreadsheets as CSV files at once, even in 2021, there does not seem to be a GUI button to do this. At least I could not see anything. The answer by #Amit Agarwal does well, to get all sheets, but if your file has comma-delimited data in cells, then data could get mangled.
I took Amit's approach https://stackoverflow.com/a/28711961 and combined it with Michael Derazon and Aaron Davis's approach here https://gist.github.com/mrkrndvs/a2c8ff518b16e9188338cb809e06ccf1 to dump all the tabs of a chosen Google spreadsheet into a folder in Google Drive. You can then just download the folder with a single click.
The following is Google script, not exactly a Javascript, and you would have to copy-paste this in https://script.google.com/ login with your Google id, and then create a project and then create a script app, and save and execute this.
// https://stackoverflow.com/a/28711961
function export_sheets_as_csv_to_folder() {
// Sheet id is in URL https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit#gid=IGNORE
var ss = SpreadsheetApp.openById('YOUR_SHEET_ID');
var sheets = ss.getSheets();
if (sheets === undefined || sheets.length === 0) {
return;
}
var passThroughFolder = DriveApp.createFolder('YOUR_PREFERRED_FOLDER_NAME_IN_DRIVE');
for (var s in sheets) {
var csv = convertRangeToCsvFile_(sheets[s])
passThroughFolder.createFile(sheets[s].getName() + ".csv", csv);
}
}
// https://gist.github.com/mrkrndvs/a2c8ff518b16e9188338cb809e06ccf1
function convertRangeToCsvFile_(sheet) {
// get available data range in the spreadsheet
var activeRange = sheet.getDataRange();
try {
var data = activeRange.getValues();
var csvFile = undefined;
// loop through the data in the range and build a string with the csv data
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
// join each row's columns
// add a carriage return to end of each row, except for the last one
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
csvFile = csv;
}
return csvFile;
}
catch(err) {
Logger.log(err);
Browser.msgBox(err);
}
}
After clicking download > pdf, select export > worksheet (instead of current sheet which is the default)
You can use Google Scripts to save all the sheets of a spreadsheet into separate files.
function myFunction() {
var ss = SpreadsheetApp.openById(SHEET_ID);
var sheets = ss.getSheets();
for (var s in sheets) {
var csv = "";
var data = sheets[s].getDataRange().getValues();
for (d in data) {
csv += data[d].join(",") + "\n";
}
DriveApp.createFile(sheets[s].getName() + ".csv", csv);
}
}
the answer from #Soham works amazingly but it doesn't handle multiline values. It would be an easy fix just to add more checks to character \n along with , but I took the liberty to rewrite the function using map (and string.includes) so it is more concise.
function convertRangeToCsvFile_(sheet) {
return sheet.getDataRange().getValues()
.map(row => row.map(value => value.toString())
.map(value => (value.includes("\n") || value.includes(",")) ? "\"" + value + "\"" : value)
.join(','))
.join('\n')
}
A slight variation on this that uses a zip instead of a folder to contain the sheets and does some modernizing of the great work done by keychera and Soham's answer.
You can use this as a bound script and it will add a menu item to the extensions menu:
// Code.gs
function exportSheetsToDrive() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheets = ss.getSheets();
if (sheets === undefined || sheets.length === 0) {
return;
}
const now = new Date();
const csvBlobs = sheets.map((sheet) => {
const name = sheet.getName();
const csv = convertSheetToCsv(sheet);
Logger.log({ name, length: csv.length });
return Utilities.newBlob(csv, MimeType.CSV, `${name}.csv`)
});
const zipName = `export_${ss.getName()}_${now.toISOString()}.zip`;
const zip = Utilities.zip(csvBlobs, zipName);
DriveApp.createFile(zip);
}
function convertSheetToCsv(sheet) {
return sheet
.getDataRange()
.getValues()
.map((row) =>
row
.map((value) => value.toString())
.map((value) =>
value.includes("\n") || value.includes(",")
? '"' + value + '"'
: value
)
.join(",")
)
.join("\n");
}
and
// Menu.gs
function onOpen(e) {
const menu = SpreadsheetApp.getUi().createAddonMenu();
menu
.addItem('Export all sheets as CSV to Drive', 'exportSheetsToDrive')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}

jquery autocomplete remote source tried EVERYTHING !! but no good

i have been trying to implement jquery ui autocomplete feature.. and the basic html code is xactly the same as given on-
http://jqueryui.com/demos/autocomplete/#remote
I have tried all combinations/ code snippets for "search.php" such as-
1)
<?php
if ( !isset($_REQUEST['term']) )
exit;
// connect to the database server and select the appropriate database for use
$dblink = mysql_connect('localhost', 'root', '') or die( mysql_error() );
mysql_select_db('research');
$rs = mysql_query('select uname,email,password from login where uname like "'. mysql_real_escape_string($_REQUEST['term']) .'%" order by uname asc limit 0,10', $dblink);
// loop through each zipcode returned and format the response for jQuery
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['uname'] .', '. $row['password'] .' '.$row['uname'] ,
'value' => $row['uname']
);
}
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>
2)
<?php
include("includes/connect.php");
$query = "SELECT uname from login WHERE uname LIKE '%" . addslashes($_GET['term']) . "%'";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
foreach($row as $val)
$tab[] = $val;
}
print json_encode($tab);
?>
3)
<?php
include("includes/connect.php");
$term = $_REQUEST['m']; // where name of the text field is 'm'
$query = "SELECT * FROM login WHERE uname LIKE '%$term%'";
$result = $mysqli->query($query);
$arr = array();
while($obj = $result->fetch_assoc()) {
$arr[] = $obj['nome'];
}
echo json_encode($arr);
?>
But still nothing is working !! that is when i type into the text box for autocomplete there are no results shown. what could be the error ? are there any alternative solutions ?? Please help !!!
The variable that you pass into json_encode must be an array of strings.
e.g. ["red","green","blue"]
or an array of object literals e.g. [{"value" : "red"},{"value" : "green"},{"value" : "blue"}]
Each time through the loop you need to append the item to the existing items.
I notice, in all 3 code snippets, that you assign the current item to your array variable, instead of appending it. When the loop completes, the only item in your array will be the item processed most recently by the loop.
So unless what you type in the field matches that one item, the autocomplete isn't going to show anything.
Here is my PHP code to build an array of strings before sending it back to the file that made the request.
$fetchedArtists = $db->query($queryToGetArtists );
$json = '[';
$first = true;
while($row = $fetchedArtists->fetch_assoc())
{
if (!$first)
{
$json .= ',';
}
else
{
$first = false;
}
$artist = $row['artistName'];
$json .= '{"value":"'.$artist.'"}';
}
$json .= ']';
echo $json;

Resources