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

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

Related

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

How to check if enabling custom invoice numbers results in duplicate invoice Numbers

I am working on integrating quick books with mvc and I have to work on one task which is to check if enabling custom invoice numbers results in duplicate Invoice .
I have tried creating invoice in quick books
public Invoice PostInvoice(InvoiceViewModel model)
{
Intuit.Ipp.Data.Invoice invoice = new Intuit.Ipp.Data.Invoice();
invoice.Deposit = new Decimal(0.00);
invoice.DepositSpecified = true;
invoice.DocNumber = "QBOInvoice" + DateTime.Now.ToString("MMddHHmmss");
invoice.CustomerRef = new ReferenceType { Value = model.qboCustomer.Id };
// invoice.CustomerMemo = new MemoRef { Value = reference };
invoice.DueDate = DateTime.UtcNow.Date;
invoice.DueDateSpecified = true;
invoice.TotalAmtSpecified = true;
invoice.ApplyTaxAfterDiscount = false;
invoice.ApplyTaxAfterDiscountSpecified = true;
invoice.PrintStatus = PrintStatusEnum.NotSet;
invoice.PrintStatusSpecified = true;
invoice.EmailStatus = EmailStatusEnum.NotSet;
invoice.EmailStatusSpecified = true;
invoice.BalanceSpecified = true;
invoice.TxnDate = DateTime.UtcNow.Date;
invoice.TxnDateSpecified = true;
invoice.ShipAddr = model.Address;
invoice.BillAddr = model.Address; //new PhysicalAddress() { Line1 = "BillMohali", Line2 = "Sector 70 ", City = "Mohali", PostalCode = "160071" };
//invoice.ShipAddr = new PhysicalAddress() {Line1="Mohali", Line2="Sector 70 ",City="Mohali",PostalCode="160071" };
//invoice.BillAddr = new PhysicalAddress() { Line1 = "BillMohali", Line2 = "Sector 70 ", City = "Mohali", PostalCode = "160071" };
Intuit.Ipp.Data.Line line = new Intuit.Ipp.Data.Line();
SalesItemLineDetail lineSalesItemLineDetail = new SalesItemLineDetail();
List<Intuit.Ipp.Data.Line> lineList = new List<Intuit.Ipp.Data.Line>();
foreach (var item in model.qbolineitems)
{
lineSalesItemLineDetail = new SalesItemLineDetail();
line = new Intuit.Ipp.Data.Line();
//Line Sales Item Line Detail - ServiceDate
lineSalesItemLineDetail.ServiceDate = DateTime.Now.Date;
lineSalesItemLineDetail.ServiceDateSpecified = true;
lineSalesItemLineDetail.Qty = item.invoiceitem.quantity.Value;
lineSalesItemLineDetail.QtySpecified = true;
lineSalesItemLineDetail.ItemRef = new ReferenceType { Value = item.item.qboItemCode.Value.ToString(), name = item.item.qboItemName };
lineSalesItemLineDetail.AnyIntuitObject = item.invoiceitem.SalePrice.Value / item.invoiceitem.quantity.Value;
lineSalesItemLineDetail.ItemElementName = ItemChoiceType.UnitPrice;
line.AnyIntuitObject = lineSalesItemLineDetail;
line.Description = item.item.qboItemName;
line.Amount = item.invoiceitem.SalePrice.Value;
line.AmountSpecified = true;
// line.Id = item.item.qboItemCode.Value.ToString();
line.DetailType = LineDetailTypeEnum.SalesItemLineDetail;
line.DetailTypeSpecified = true;
//if (_connect.Country == "US")
//{
lineSalesItemLineDetail.TaxInclusiveAmt = item.invoiceitem.SalePrice.Value;
lineSalesItemLineDetail.TaxCodeRef = new ReferenceType { Value = "TAX" };
//}
//else
//{
//_connect = (Connect)Session["Connect"];
// objQBO = new QBOWrapper("jagjeetkr7#gmail.com", Request.Url.GetLeftPart(UriPartial.Authority) + "/Home/Callback", _connect, true);
//var taxcode = objQBO.getTaxCodeList().Where(x => x.Active).FirstOrDefault();
//lineSalesItemLineDetail.TaxCodeRef = new ReferenceType { Value = taxcode.Id };
//var dis = item.invoiceitem.SalePrice.Value / (Convert.ToDecimal(taxcode.SalesTaxRateList.TaxRateDetail[0].TaxRateRef.Value) + 1);
//line.Amount = item.invoiceitem.SalePrice.Value - dis;
//lineSalesItemLineDetail.TaxInclusiveAmt = item.invoiceitem.SalePrice.Value;
lineSalesItemLineDetail.TaxInclusiveAmtSpecified = false;
invoice.GlobalTaxCalculationSpecified = false;
invoice.GlobalTaxCalculation = GlobalTaxCalculationEnum.NotApplicable;
//SendInsideFunctionEmail("Failed to create surcharge invoice for : " + reference, "Please create a surcharge invoice manually and send a receipt to the customer. Also,please assign the tax code for this account selected in qbo.", _generalSettings.AccountsEmail);
// }
lineList.Add(line);
}
//invoice.TotalAmt = new Decimal(0.90);
//invoice.Balance = new Decimal(0.90);
// xlic.Add(li);
invoice.TotalAmt = model.Total;
invoice.Balance = model.BalanceDue;
invoice.Line = lineList.ToArray();
_connect = (Connect)Session["Connect"];
objQBO = new QBOWrapper("jagjeetkr7#gmail.com", Request.Url.GetLeftPart(UriPartial.Authority) + "/Home/Callback", _connect, true);
//objQBO = new QBOWrapper("jagjeetkr7#gmail.com", Request.Url.GetLeftPart(UriPartial.Authority) + "/Home/Callback", _connect, true);
invoice = objQBO.CreateInvoice(invoice);
return invoice;
}
I expect that generating custom invoice numbers results in duplicate invoice but not finding a way to implement that

PHPPowerpoint set Hyperlink in table cell

I want to set an Hyperlink in a table cell:
/* ADD TABLE ROW */
foreach ($entries as $entry) {
$row = $tableShape->createRow();
$row->getFill()->setFillType(Fill::FILL_SOLID)
->setStartColor(new Color('FFFFFFFF'))
->setEndColor(new Color('FFFFFFFF'));
$row->nextCell()->createTextRun(date_format($entry->getDate(), "d.m.Y"));
$row->nextCell()->createTextRun($entry->getTonality()->getName());
$row->nextCell()->createTextRun($entry->getAccountname());
$row->nextCell()->createTextRun($entry->getContent());
$row->nextCell()->createTextRun($entry->getFollower());
$row->nextCell()->createTextRun($entry->getLink());
}
This code doesn't work:
$row->nextCell()->createTextRun('Link')->setUrl($entry->getLink())
->setTooltip('Link');;
I'm doing it now by adding a shape on the right position.
/* SET HYPERLINK WITH SHAPE */
$shape = $slide->createRichTextShape();
$shape->setWidth($this->cell_link_width)
->setHeight($this->cell_height)
->setOffsetX($this->cell_link_offsetX)
>setOffsetY($this->tableOffsetY + $height);
$textLink = $shape->createTextRun('Link');
$textLink->getHyperlink()->setUrl('http://' . $entry->getLink())
>setTooltip('http://' . $entry->getLink());
I have write an algorithmus and define a variable line_height to set the link on the right position.
Here is my complete function:
public function createTableSlide($objPHPPowerPoint, $pathLogo, $user, $entries) {
$slide = $this->createTemplatedSlide($objPHPPowerPoint, $pathLogo, $user);
/* CREATE TABLE WITH COLUMNS */
$tableShape = $this->getTable($slide, 6);
$this->setTableSlideHeader($slide, 'Social Media', 'Twitter', $tableShape);
/* ADD TABLE ROW */
$i = 1;
$height = 22;
$height_tmp = 0;
$max_height = 554;
foreach ($entries as $entry) {
$height += $height_tmp;
$modulId = $entry->getModul()->getId();
/* NEW SLIDE IF TABLE HEIGHT AT END OF SLIDE */
if($height >= $max_height){
$slide = $this->createTemplatedSlide($objPHPPowerPoint, $pathLogo, $user);
/* CREATE TABLE WITH COLUMNS */
$tableShape = $this->getTable($slide, 6);
$this->setTableSlideHeader($slide, 'Social Media', 'Twitter', $tableShape);
$i = 1;
$height = 22;
$height_tmp = 0;
}
$row_in_cell = ceil(strlen($entry->getContent()) / $this->char_in_row);
if ($row_in_cell > 2) {
$height_tmp = $row_in_cell * $this->line_height + $this->line_height;
} else {
$height_tmp = $this->line_height * 3 + 0.8;
}
$row = $tableShape->createRow();
$row->setHeight($this->cell_height);
$row->getFill()->setFillType(Fill::FILL_SOLID)
->setStartColor(new Color('FFFFFFFF'))
->setEndColor(new Color('FFFFFFFF'));
$row->nextCell()->createTextRun(date_format($entry->getDate(), "d.m.Y"));
$row->nextCell()->createTextRun($entry->getTonality()->getName());
$row->nextCell()->createTextRun($entry->getAccountname());
$row->nextCell()->createTextRun($entry->getContent());
$row->nextCell()->createTextRun($entry->getFollower());
$row->nextCell()->createTextRun($modulId);
/* SET HYPERLINK WITH SHAPE */
$shape = $slide->createRichTextShape();
$shape->setWidth($this->cell_link_width)
->setHeight($this->cell_height)
->setOffsetX($this->cell_link_offsetX)
->setOffsetY($this->tableOffsetY + $height);
$textLink = $shape->createTextRun('Link');
$textLink->getHyperlink()->setUrl('http://' . $entry->getLink())
->setTooltip('http://' . $entry->getLink());
$i++;
}
}
Hope it can help you if you search for the same solution. If anyone has a better solution he can answer me :)
The issue has been fixed in the develop branch.
Link : https://github.com/PHPOffice/PHPPowerPoint/commit/43bea92220396a3c7178f649afbc961be28828c1

How to copy one spreadsheet's cell to another spreadsheet

I tried coding like spreadsheet API batch copy https://developers.google.com/google-apps/spreadsheets/#updating_multiple_cells_with_a_batch_request, The sample is base on same spreadsheet, I added a target cell but always get same error
com.google.gdata.client.batch.BatchInterruptedException: Batch Interrupted (some operations might have succeeded) : a response has already been sent for batch operation update id='R1C1'
My code like this
SpreadsheetService spreadsheetService = getSpreadsheetService(currentEmail);
WorksheetFeed feed = spreadsheetService.getFeed(getWorksheetFeedURL(sourceId), WorksheetFeed.class);
SpreadsheetEntry targetFeed = spreadsheetService.getEntry(getSpreadsheetFeedURL(targetId), SpreadsheetEntry.class);
SpreadsheetEntry sourceFeed = spreadsheetService.getEntry(getSpreadsheetFeedURL(sourceId), SpreadsheetEntry.class);
for(WorksheetEntry entry:feed.getEntries()){
WorksheetEntry targetWorksheet = spreadsheetService.insert(targetFeed.getWorksheetFeedUrl(), entry);
FeedURLFactory urlFactory = FeedURLFactory.getDefault();
URL cellFeedUrl = urlFactory.getCellFeedUrl(sourceFeed.getKey(), "od6", "private", "full");
URL targetFeedUrl = urlFactory.getCellFeedUrl(targetFeed.getKey(), "od6", "private", "full");
CellFeed cellFeed = spreadsheetService.getFeed(targetFeedUrl, CellFeed.class);
List<CellAddress> cellAddrs = new ArrayList<CellAddress>();
for (int row = 1; row <= entry.getRowCount(); ++row) {
for (int col = 1; col <= entry.getColCount(); ++col) {
cellAddrs.add(new CellAddress(row, col));
}
}
Map<String, CellEntry> cellEntries = getCellEntryMap(spreadsheetService, cellFeedUrl, cellAddrs);
CellFeed batchRequest = new CellFeed();
for (CellAddress cellAddr : cellAddrs) {
URL entryUrl = new URL(targetFeedUrl.toString() + "/" + cellAddr.idString);
CellEntry batchEntry = new CellEntry(cellAddr.row, cellAddr.col, cellAddr.idString);
String inputValue = cellEntries.get(cellAddr.idString).getCell().getInputValue();
batchEntry.changeInputValueLocal(inputValue);
batchEntry.setId(String.format("%s/%s", targetFeedUrl.toString(), cellAddr.idString));
System.out.println(targetFeedUrl.toString()+": "+cellAddr.idString+" "+ inputValue);
BatchUtils.setBatchId(batchEntry, cellAddr.idString);
BatchUtils.setBatchOperationType(batchEntry, BatchOperationType.UPDATE);
batchRequest.getEntries().add(batchEntry);
}
spreadsheetService.setHeader("If-Match", "*");
// Submit the update
Link batchLink = cellFeed.getLink(ILink.Rel.FEED_BATCH, ILink.Type.ATOM);
CellFeed batchResponse = spreadsheetService.batch(new URL(batchLink.getHref()), batchRequest);
boolean isSuccess = true;
for (CellEntry entry1 : batchResponse.getEntries()) {
String batchId = BatchUtils.getBatchId(entry);
if (!BatchUtils.isSuccess(entry1)) {
isSuccess = false;
BatchStatus status = BatchUtils.getBatchStatus(entry);
}
}
spreadsheetService.setHeader("If-Match", null);
Batch copy:
What is the fastest way to update a google spreadsheet with a lot of data through the spreadsheet api?
There is a Bug with cell references such as $A5.
They will not write to the spreadsheet. While both A5 and $A$5 work, references with just one $ in cause a problem. I forget the fine detail.

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;

Resources