I have the following code that does a great job sending data to excel sheet. In the database I have values under a column say k i have values which are comma separated e.g. alphonce, ochieng, abc, so for each value/word, i want to create a new row so that alphonce is in the new row in a given cell same as ochieng etc, like generated table rows holding the names.
$trd = $this->getRequestedTestsDisplay2($labref);
$coa_details = $this->getAssayDissSummary($labref);
$row = 26;
$worksheet = $objPHPExcel->getActiveSheet();
for ($i = 0; $i < count($trd); $i++) {
$col = 1;
foreach ($coa_details as $coa) {
if ($coa->test_id == $trd[$i]->test_id) {
$determined = $coa->determined;
$remarks = $coa->verdict;
}
}
$worksheet
->setCellValueByColumnAndRow($col++, $row, $trd[$i]->name)
->setCellValueByColumnAndRow($col++, $row, $trd[$i]->methods)
->setCellValueByColumnAndRow($col++, $row, $trd[$i]->compedia);
$worksheet->setCellValueByColumnAndRow($col++, $row, str_replace(",", "\n", $trd[$i]->specification));
$worksheet->setCellValueByColumnAndRow($col++, $row, str_replace(",", "\n",$determined));
$worksheet->setCellValueByColumnAndRow($col++, $row, str_replace(",", "\n", $trd[$i]->complies));
$worksheet->getStyle($col++ . $row)->getAlignment()->setWrapText(true);
$worksheet->getRowDimension($row)->setRowHeight(-1);
$row++;
}
}
$myData = "Hello,World";
// Write data to cell A1, replacing comma with a new line character
$worksheet->setCellValueByColumnAndRow(1, 1, str_replace(",", "\n", $myData));
// Set the cell alignment to wrap the text
$worksheet->getStyle('A1')->getAlignment()->setWrapText(true);
// Set the row height to automatically adjust to the number of lines
// of data in the cell
$worksheet->getRowDimension(1)->setRowHeight(-1);
Related
I am trying to import a grade sheet into mysql database but that excel file have multiple sheet how can i make it so only a specified sheet will be going into my database
$uploadfile=$_FILES['uploadfile']['tmp_name'];
require 'PHPExcel/Classes/PHPExcel.php';
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objExcel =PHPExcel_IOFactory::load($uploadfile);
foreach($objExcel->getWorksheetIterator() as $worksheet)
{
$highestrow=$worksheet->getHighestRow();
for($row=8;$row<=$highestrow;$row++){
$name=$worksheet->getCellByColumnAndRow(1,$row)->getValue();
$finalgrade=$worksheet->getCellByColumnAndRow(15,$row)->getValue();
if($finalgrade != ''){
$insertqry = "INSERT INTO `user`(`stud_name`, `final_grade`) VALUES ('$name',' $finalgrade')";
$insertres = mysqli_query($con,$insertqry);
}
}
}
As far as I understand you are looking to get data from a specific sheet.
In PHPExcel there is this function: setActiveSheetIndex(sheet_index)
You can try like this:
$uploadfile = 'test.xlsx';
$objExcel = PHPExcel_IOFactory::load($uploadfile);
$objData = PHPExcel_IOFactory::createReader('Excel2007');
//read only
$objData->setReadDataOnly(true);
$objPHPExcel = $objData->load($uploadfile);
// Select sheet to get
$sheet = $objPHPExcel->setActiveSheetIndex(1);
$Totalrow = $sheet->getHighestRow();
$LastColumn = $sheet->getHighestColumn();
$TotalCol = PHPExcel_Cell::columnIndexFromString($LastColumn);
$data = [];
// Proceed to loop through each data cell
// Repeat rows, Since the first row is assumed to be the column header, we will loop the value from line 2
for ($i = 2; $i <= $Totalrow; $i++) {
//---- Loop column
for ($j = 0; $j < $TotalCol; $j++) {
// Proceed to get the value of each cell into the array
$data[$i - 2][$j] = $sheet->getCellByColumnAndRow($j, $i)->getValue();;
}
}
var_dump($data);
i just deleted the foreach and add getSheetName()
require 'PHPExcel/Classes/PHPExcel.php';
require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objExcel =PHPExcel_IOFactory::load($uploadfile);
$worksheet = $objExcel->getSheetByName('GEN.AVERAGE');
$highestrow=$worksheet->getHighestRow();
for($row=8;$row<=$highestrow;$row++){
$name=$worksheet->getCellByColumnAndRow(1,$row)->getValue();
$finalgrade=$worksheet->getCellByColumnAndRow(15,$row)->getValue();
if($finalgrade != ''){
$insertqry = "INSERT INTO `user`(`stud_name`, `final_grade`) VALUES ('$name',' $finalgrade')";
$insertres = mysqli_query($con,$insertqry);
}
}
Hello i have an import of an xls file with multiple rows on it and i want to insert them into database only if the price columns has a value different than nothing else display an error msg. It works on half it only inserts those rows that have a value for price but instead returning the html error msg it returns the sql msg, that means it goes on the else branch.
Here is my code
$exceldata = array();
$uploadFilePath = 'uploads/'.basename($_FILES['doc']['name']);
move_uploaded_file($_FILES['doc']['tmp_name'], $uploadFilePath);
$inputfilename = 'uploads/'.$_FILES['doc']['name'].'';
// Read your Excel workbook
try
{
$inputfiletype = PHPExcel_IOFactory::identify($inputfilename);
$objReader = PHPExcel_IOFactory::createReader($inputfiletype);
$objPHPExcel = $objReader->load($inputfilename);
}
catch(Exception $e)
{
die('Error loading file "'.pathinfo($inputfilename,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$header=$_POST['membership'];
if($header==1)
{
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++)
{
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
if ($rowData[0][9]=='')
{
echo 'No price for the product '.$rowData[0][1].'';
}
else
{
$a = array('8', '1', '2', '3', '4', '5','6');
$b = array($rowData[0][0], $rowData[0][2], $rowData[0][3],$rowData[0][5],$rowData[0][6],$rowData[0][8],$rowData[0][8]);
$c = array_combine($a, $b);
$slug = str_replace(" ", "-",$rowData[0][1]);
$slug = str_replace('"', "",$slug);
$slug = str_replace('/', "-",$slug);
$stmt=$dbh->prepare("INSERT INTO tbl_products (name,slug,description,price)
VALUES (:name,:slug,:desc,:pret)");
$stmt->bindParam(":name",$rowData[0][1]);
$stmt->bindParam(":slug",$slug);
$stmt->bindParam(":desc",$rowData[0][10]);
$stmt->bindParam(":pret",$rowData[0][9]);
$stmt->execute();
$id_product=$dbh->lastInsertId();
$stmt=$dbh->prepare("INSERT INTO tbl_products_images_gallery (id_product,name,image,sort_order)
VALUES (:id,:name,:image,100)");
$stmt->bindParam(":id",$id_product);
$stmt->bindParam(":name",$rowData[0][4]);
$stmt->bindParam(":image",$slug);
$stmt->execute();
$stmt=$dbh->prepare("SELECT id_category from tbl_catalog_categories where name=:name");
$stmt->bindParam(":name",$rowData[0][2]);
$stmt->execute();
if($row=$stmt->fetch())
{
$id_cat=$row['id_category'];
}
$stmt=$dbh->prepare("INSERT INTO tbl_products_to_categories (id_category,id_product)
VALUES (:id_cat,:id_prod)");
$stmt->bindParam(":id_cat",$id_cat);
$stmt->bindParam(":id_prod",$id_product);
$stmt->execute();
foreach($c as $key => $value)
{
$stmt=$dbh->prepare("INSERT INTO tbl_products_attributes_values (id_product,id_attribute,attribute_value)
VALUES (:id_product,:id_attribute,:value)");
$stmt->bindParam(":id_product",$id_product);
$stmt->bindParam(":id_attribute",$key);
$stmt->bindParam(":value",$value);
$stmt->execute();
}
}
}
}
if (empty($rowData[0][9])) perhaps?
Or test for null as well as for empty strings - nulls are perfectly valid response from PHPExcel...
especially as
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
with it's null second argument is telling PHPExcel to return a null value if the cell simply doesn't exist in the spreadsheet
Though you can change the rangeToArray() call to
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, '', TRUE, FALSE);
to return an empty string instead of a null if the cell doesn't exist
I'm using the column header as an array index (row 1), and I don't want to have problems when they start uploading their XLSX file with incorrect column headers (or sometimes missing).
I found this answer really useful. I can make my array indexes as column headers:
for ($row = 2; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
$rowData[0] = array_combine($headings[0], $rowData[0]);
}
The code above is from https://stackoverflow.com/a/32526911/8191721
Here's what I want to happen:
Check first the column headers if they matches with the column
headers I provided (in array, so I can use in_array in a loop) before
writing it to the database.
If the headers are correct, I will now turn the array indexes to column headers (so instead of [0], it should now return [firstname]) or else throw an error message.
Write to database where the column names in my database exactly matches the column header names (or if not, at least matches the query) in their XLSX file. (I called them "column mapping").
Long story short, here's my code:
try {
$inputFileName = $_FILES['file']['tmp_name'];
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
//-- Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$headings = $sheet->rangeToArray('A1:'.$highestColumn.'1', NULL, TRUE, FALSE);
//-- $row = 2 <- skip row 1 since this is our headers
for($row = 2; $row <= $highestRow; $row++) {
//-- Read a row of data into an array
$xlsxRow = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
//-- Combine to replace indexes with header names
$xlsxRow[0] = array_combine($headings[0], $xlsxRow[0]);
//-- Got stucked in here..
/*
If column header fails, should exit the loop
*/
//-- SQL query follows here..
}
So can someone help me figuring this out?
To compare the header value you can use array_diff() function.
If you want to give more flexibility to user then you can use following example.
In this case use
$excelSheetHeaders = array();
for ($i = 1; $i <= 1; $i++) {
$rowData = $sheet->rangeToArray('A' . $i . ':' . $highestColumn . $i, NULL, TRUE, FALSE);
$excelSheetHeaders = $rowData[0];
$excelSheetHeaders = array_map('strtolower', $excelSheetHeaders);
$errorCount = 0;
foreach ($headerArray as $index => $value){
if(!in_array(strtolower($value), $excelSheetHeaders)){
$errorCount++;
}
}
if($errorCount > 0){
//Throw Error and exit;
}
}
for ($i = 2; $i <= $highestRow; $i++){
$rowData = $sheet->rangeToArray('A' . $i . ':' . $highestColumn . $i,NULL,TRUE,FALSE);
$spreadsheetData = array();
foreach($headerArray as $index => $value){
$spreadsheetData[$value] = $rowData[0][array_search(strtolower($value),$excelSheetHeaders)];
}
var_dump($spreadsheetData);
}
This error is exactly what you want. Now you can access $spreadsheetData['firstName'].
I have a csv file with some records and each record has unique ID. I'm running a loop to find that unique ID and then append some more data to that record.
Is it possible to do this without a temporary file? Creating such file and moving all data in it takes more time...
My code is:
<?php
$temp = fopen('tempwin.csv','w+');
if (($handle = fopen("win.csv", "r+")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
if($data[4] == trim($leadid)){
$data[5] = trim($_POST['year']);
$data[6] = trim($_POST['make']);
$data[7] = trim($_POST['model']);
$data[8] = trim($_POST['trade']);
}
}
fputcsv($temp, $data);
}
fclose($handle);
fclose($temp);
}
unlink('win.csv');
rename('tempwin.csv','win.csv');
You can use following, but you need to pass the row number i.e where you need to add row.
<?php
//A helping function to insert data at any position in array.
function array_insert($array, $pos, $val)
{
$array2 = array_splice($array, $pos);
$array[] = $val;
$array = array_merge($array, $array2);
return $array;
}
//What and where you want to insert
$DataToInsert = '11,Shamit,Male';
$PositionToInsert = 3;
//Full path & Name of the CSV File
$FileName = 'data.csv';
//Read the file and get is as a array of lines.
$arrLines = file($FileName);
//Insert data into this array.
$Result = array_insert($arrLines, $PositionToInsert, $DataToInsert);
//Convert result array to string.
$ResultStr = implode("\n", $Result);
//Write to the file.
file_put_contents($FileName, $ResultStr);
?>
Fetch the data out of the original file as an array or string, make your modifications and then simply overwrite the contents of the file with your modified data.
I have PHPExcel plugin to generated excel which data came from database, how if I wanted to add in additional text into a column A during the loop, and column B remain untouched data as from DB?
For example column A in DB is
alex
andy
jennifer
when output to excel, I wanted to add #domain.com for each name behind, wich will become
alex#domain.com
andy#domain.com
jennifer#domain.com
Code:
$query = "SELECT mail_name, account_id FROM email ORDER BY mail_name ASC";
$headings = array('Email', 'Id');
if ($result = mysql_query($query) or die(mysql_error())) {
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('emailList');
$rowNumber = 1;
$col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
// Loop through the result set
$rowNumber = 1;
while ($row = mysql_fetch_row($result)) {
$col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
Keep in mind that $col++ is not going to work.
What about this way?:
// Loop through the result set
$rowNumber = 1;
while ($row = mysql_fetch_row($result)) {
$objPHPExcel->getActiveSheet()
->setCellValue('A'.$rowNumber,$row['mail_name'].'#domain.com');
$objPHPExcel->getActiveSheet()
->setCellValue('B'.$rowNumber,$row['account_id']);
++$rowNumber;
}