PhpSpreadsheet Notice: Undefined offset: 4 - phpspreadsheet

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

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

How to read spreadsheet with no scientific notation?

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

php textarea save as shown in

textarea automaticlly makes a new line when the text reaches the end window.
save the text in *.txt me stored in a line.
How to save the text in the form that I see?
if in php?
enter code here
if(isset($_POST['submit'])){
//narredi file
$ourFileName = "baza/$file1.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
//konec naredi
//shrani besedilo
$area=$_REQUEST['area'];
//$area12 = explode(" ", $area);
//$area12 = str_replace('\n', '<br />', $area);
$text = trim($_POST['area']); // remove the last \n or whitespace character
$text = nl2br($text);
$loadcontent = "baza/$file1.txt";
$fd=fopen("$loadcontent", "w+") or die("can't open file");
fwrite($fd,$text);
fclose($fd);
$file_contents=file_get_contents("baza/$file1.txt");
<textarea name="area" id="Data" wrap="on" cols=100 rows=5 >
test
testttt
testt</textarea>
<br>
<input type="submit" name="submit" value="Objavi" />
I have defined textarea size (css), and when I write the text longer of visible window then it create a visible new line in fact one line. I want two line or more....
for me it is so good
$vrst = explode("\n", $loadcontent1);
$vrst1 = count($vrst);
$a = 0;
StartOfLoop:
$lines = array_slice(explode("\n", $loadcontent1), "$a", 1);
$stevil = strlen($loadcontent1);
$stevilo = $stevil / 88;
$stringpred = implode("\n", $lines);
$trimmed1 = strlen($stringpred);
$vrstic = $trimmed1/88+1;
if (88 > $trimmed1) goto pogojzavec;
foreach ($lines as $key => $value)
{
$a=0;
do
{
$lines[$key] = substr(trim($value), "$a", "88+$a");
$string = implode("\n", $lines);
$stringg11 = $string;
$stringg2 = "$stringg2\n$stringg11";
$a =$a +88;
}
while ($a<=$trimmed1);
}
goto preskok;
pogojzavec:
foreach ($lines as $key => $value)
{
$lines[$key] = substr(trim($value), 0, 88);
}
$string = implode("\n", $lines);
$stringg11 = $string;
$stringg2 = "$stringg2\n$stringg11";
preskok:
$a = $a + 1;
if($a < $vrst1) goto StartOfLoop;

Want several font colors in my cell

Im creating a new cell = new XRTableCell();
I'll show a sample of my code.
I always ending up with the same color in my cell, even if I change it in my "If".
foreach (TaskTime tt in di.TaskTimes[i])
{
.....
TimeToAdd = ClassLibrary.Utils.GetTimeStringFromSec(tt.FromSec % 86400) + " - " + ClassLibrary.Utils.GetTimeStringFromSec(tt.UntilSec % 86400) + " (" + tt.Abbreviation+ ")";
if (taskTimeTextBox.Text.Length > 0)
taskTimeTextBox.Text += "\n";
taskTimeTextBox.Text += TimeToAdd;
if (tt.OnOtherCostDivision)
{
taskTimeTextBox.SelectionStart = taskTimeTextBox.Find(TimeToAdd);
taskTimeTextBox.SelectionFont = new Font("Calibri", 9, FontStyle.Italic);
taskTimeTextBox.SelectionColor = Color.Gray;
}
else
{
taskTimeTextBox.SelectionStart = taskTimeTextBox.Find(TimeToAdd);
taskTimeTextBox.SelectionFont = new Font("Calibri", 9, FontStyle.Italic);
taskTimeTextBox.SelectionColor = Color.Blue;
}
richTxtObject.Rtf = taskTimeTextBox.Rtf;
cell.Controls.Add(richTxtObject);
}
row.Cells.Add(cell);
Soulved it! Didn't worked when I had it this way "taskTimeTextBox.Text += xxxxxxxx ". So I made a list of string, saved my text in if it were "onOtherCostDivision". Later on I hade to loop true my list and see if the final taskTimeTextBox.Text had the text in it and in that cause I added the color.
foreach (var task in taskCostDivList)
{
if (taskTimeTextBox.Text.Contains(task))
{
taskTimeTextBox.SelectionStart = taskTimeTextBox.Find(task);
taskTimeTextBox.Font = new Font("Calibri", 9, FontStyle.Italic);
taskTimeTextBox.SelectionColor = Color.Gray;
}
else
{
taskTimeTextBox.Font = new Font("Calibri", 9, FontStyle.Regular);
taskTimeTextBox.SelectionColor = Color.Black;
}
}

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