I want to upload an Excel file into our webpage, then corresponding data store it in database. And then I want to retrieve all data and display it in table format. I have one code but using that I can't upload all Excel files. Only a single format can be upload.
Below is the function. But there is some restriction.
public function check_excel($filename)
{
$path='./assets/uploads/excel/'.$filename;
$this->load->library('excel');
$inputFileType = PHPExcel_IOFactory::identify($path);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = PHPExcel_IOFactory::load($path);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$xf[]='';
$result[]='';
$first_check='';
$var_check=0;
for ($row = 13; $row <= $highestRow; $row++)
{
$xf[$row]=$objPHPExcel->getActiveSheet()->getCell('A'.$row)->getXfIndex(); // Get sheet index value
if($row>13 && $row<16) //This block check first kpi data expand or not
{
if($xf[$row-1]==$xf[$row]) //check parent and child sheet index value same
$first_check='false';
if ($row==15)
{
if($xf[$row]==$xf[$row-1] || $xf[$row]==$xf[$row-2]) // check the grand-child sheet index value same in parent and child
$first_check='false';
else
{
$first_check='true';
$a=$row-2;
$b=$row-1;
$check_kpi=$objPHPExcel->getActiveSheet()->getCell('A'.$a)->getXfIndex();
$check_unit=$objPHPExcel->getActiveSheet()->getCell('A'.$b)->getXfIndex();
$check_sub_unit=$objPHPExcel->getActiveSheet()->getCell('A'.$row)->getXfIndex();
}
}
}
if($first_check=='true') //This block check second kpi to upto last kpi data expand or not
{
if($row>15)
{
if($var_check==1) // This block check the child data expand or not
{
if($check_unit!=$objPHPExcel->getActiveSheet()->getCell('A'.$row)->getXfIndex())
{
$result[$row]='false';
break;
}
}
if($var_check==2) // this block check the grand - child data expand or not
{
if($check_sub_unit!=$objPHPExcel->getActiveSheet()->getCell('A'.$row)->getXfIndex())
{
$result[$row]='false';
break;
}
}
if($xf[$row]!=$check_sub_unit)
{
if($xf[$row]!=$check_unit)
$var_check=1; // var_check value is one, the kpi is present
else
$var_check=2; // var_check value is two, the unit is present
}
else
$var_check=0; // var_check value is zero, the sub_unit is present
}
}
else if($first_check=='false')
{
$result[$row]='false';
break;
}
}
$return='true';
for ($row = 13; $row <= $highestRow; $row++)
{
if(!empty($result[$row]))
{
if($result[$row]=='false'){
$return='false';
break;
}
}
}
return $return;
}
It sounds like you are using a relational DB (e.g. MySQL, Postgres, etc), which uses fixed column tables.
You should probably use a Document-based DB (e.g. CouchDB, Mongo, etc). This would be the best solution.
But, if you're stuck using a relational DB, you can use an EAV model.
Here is a basic example:
Create a table for the entity (excel file): EntityID, ExcelFileName
Create a table for the attribute (column info): AttributeID, EntityID, AttributeName
Create a table for the value (excel row/column): ValueID, RowNumber, AttributeID, AttributeValue
The downside is that the AttributeValue isn't specifically typed (it's just varchar/text). You can solve this by adding a "AttributeType" to the attribute table that is then used in your code to know what type of data that column should contain. BUT, unless you know the contents/format of the Excel file in advance, you'll probably have to GUESS what the type of a column is...which isn't hard as long as the excel file isn't messed up.
If you're just displaying the data that was imported, this probably isn't a big deal.
There are other (more complex) ways to implement EAV, including one with typed columns, if you have such a need.
Have you tried PHPExcel?
They also have a codeigniter library.
And this post might interest you : how to use phpexcel to read data and insert into database?
You can use PHPExcel of course, but have a look at other data format. Using comma-separated or tab-separated values can help you to solve your problem easily. Excel can save datasheets in these simple formats. Anyway, you cannot save formulas or conditional formatting in you database Moreover, it is much faster and robust and you can import CSV files with LOAD DATA INFILE query.
Related
I am having trouble saving the excel file in mysql database, It contains enter(new line) inside a cell and symbols & superscripts as well. But it stores as plain text only.
$objReader = new PHPExcel_Reader_Excel5();
$objPHPExcel = $objReader->load($inputFileName);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
then i read some data and use
reset($sheetData);
to reset the pointer.
and again use foreach() loop, to add the data into an array and insert that array to mysql table. Does any of these steps remove pre-formatting (superscript/subscript/new line inside a cell and bold/italics)? and How can I put the data in the table exactly as in the excel?
Edit: I am using v1.8 of PHPExcel, v5.4 of PHP and MySQL v5.6
include APPPATH.'/spreadsheetreader/php-excel-reader/excel_reader2.php';
require(APPPATH.'/spreadsheetreader/SpreadsheetReader.php');
require(APPPATH.'/spreadsheetreader/SpreadsheetReader_CSV.php');
require(APPPATH.'/spreadsheetreader/SpreadsheetReader_ODS.php');
require(APPPATH.'/spreadsheetreader/SpreadsheetReader_XLS.php');
require(APPPATH.'/spreadsheetreader/SpreadsheetReader_XLSX.php');
class Dashboard extends REST_Controller
{
public function __construct()
{
parent:: __construct();
$this->load->library("PHPExcel");
}
public function dashboard_post()
{
$Reader = new SpreadsheetReader('./upload/'.$filename);
$totalSheet = count($Reader->sheets());
//print_r($totalSheet);exit;
// For Loop for all sheets
if($totalSheet>0)
{
for($i=0;$i<$totalSheet;$i++)
{
$Reader->ChangeSheet($i);
foreach ($Reader as $Row)
{
$data=array(
'your table column name'=>isset($Row[1]) ? $Row[1] : '',
'your table column name'=>isset($Row[2]) ? $Row[2] : '',
'your table column name'=>isset($Row[3]) ? $Row[3] : '',
'your table column name'=>isset($Row[4]) ? $Row[4] : '',);
}
The toArray() method is intended to provide a simple function to get the plain text from data cells in a spreadsheet; so all "formatting" of rich text (cells that contain different styles, colours, newlines and font information for different parts of the cell content) is removed to provide that plain text.
If you want to access that style information, then you need to get the data from the individual cells yourself using the cell's getValue() method; so you'll need to write your own loop to do that for all cells in the sheet; and you'll need to decide how you're going to store things like superscripts or bold/italic/underline in your database, and parse rich-text cell data accordingly
Here's the scenario, I want to be able to run a specific section of PHP code for each different excel sheet, so basically if I have a workbook that has the following sheets, "Funds", "Accounts", "Spending Data", how can I look through each sheet to be able to run separate code depending on the sheet name, so for example, I only want to fetch the cell data from A5:D5 on "Funds", but on "Accounts" I want to get the A5:P5, etc.
I've tried using the foreach ($objPHPExcel->getWorksheetIterator() as $worksheet), but that just loops through each sheet, which I would expect it to do then runs the same code on each sheet which is not what I'm looking for.
Sorry if I've not explained it very well, but if there was someway I could do something like;
if sheetname == "Funds" {
//get cells A5:D5
}
if sheetname == "Accounts" {
//get cells A5:P5
}
etc...
Any help would be greatly appreciated.
Many thanks in advance.
Kind regards.
Use getTitle to know the sheet's title:
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)
{
$sheetname = $worksheet->getTitle();
if ($sheetname == "Funds")
{
//get cells A5:D5
}
if ($sheetname == "Accounts")
{
//get cells A5:P5
}
}
I have the following Excel file:
I read it in by looping over every cell and getting the value with getCell(...)->getValue():
$highestColumnAsLetters = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestColumn(); //e.g. 'AK'
$highestRowNumber = $this->objPHPExcel->setActiveSheetIndex(0)->getHighestRow();
$highestColumnAsLetters++;
for ($row = 1; $row < $highestRowNumber + 1; $row++) {
$dataset = array();
for ($columnAsLetters = 'A'; $columnAsLetters != $highestColumnAsLetters; $columnAsLetters++) {
$dataset[] = $this->objPHPExcel->setActiveSheetIndex(0)->getCell($columnAsLetters.$row)->getValue();
if ($row == 1)
{
$this->column_names[] = $columnAsLetters;
}
}
$this->datasets[] = $dataset;
}
However, although it reads in the data fine, it reads in the calculations literally:
I understand from discussions like this one that I can use getCalculatedValue() for calculated cells.
The problem is that in the Excel sheets I am importing, I do not know beforehand which cells are calculated and which are not.
Is there a way for me to read in the value of a cell in a way that automatically gets the value if it has a simple value and gets the result of the calculation if it is a calculation?
Answer:
It turns out that getCalculatedValue() works for all cells, makes me wonder why this isn't the default for getValue() since I would think one would usually want the value of the calculations instead of the equations themselves, in any case this works:
...->getCell($columnAsLetters.$row)->getCalculatedValue();
getCalculatedValue() seems to work for all cells, see above
If you are unsure about the content of a cell (value or formula included),
I recommend you to primarily do a check if the cell has a formula and then copy - paste accordingly. getOldCalculatedValue() is very helpful in this case. Here is an example of that:
$code = $sheet->getCell('A'.$y)->getValue();
if(strstr($code,'=')==true)
{
$code = $sheet->getCell('A'.$y)->getOldCalculatedValue();
}
$objPHPExcel4->setActiveSheetIndex(0)
->setCellValue('A'.$l, $code);
For large data sets, getCalculatedValue() function is really cumbersome and lots of memory will be required to perform correctly.
Looks like getCalculatedValue() is deprecated. Try using getFormattedValue() instead.
getCalculatedValue() seems to do the right job you wanted. It will return the correct value if the cell contains FBV ( formula based value ). If not then the normal value will be returned instead.
getCalculatedValue
seems to work for all cells
$sheets = $spreadsheet->getAllSheets();
$priceCasegetCellByColumnAndRow = $sheet->getCellByColumnAndRow(14, ($key))->getCalculatedValue()
$priceCasegetCell = $sheet->getCell('O' . $key)->getCalculatedValue();
I have never imported an excel file in PHP so this is just a stab in the dark.
Why not check the first character in the cell for an "="
If true getCalculatedValue()
if not getCell()
I would like to write into a csv file using PHPEXCEL in the following format. The class in bold and a space after every class group.
But i have not been able to find a way to do it.
Here is what I could do.
I generate the data from an sql and loop thought it. Here is my code
$sql="SELECT * FROM table ORDER BY typeclass";
$query=mysql_query($sql);
$check='';
$i=1;
while($row=mysql_fetch_assoc($query))
{
if($row['class']!=$check)
{
$objPHPExcel->getActiveSheet()->setCellValue('A'.$i,$row['Class']);
$check=$row['class'];
}
$objPHPExcel->getActiveSheet()->setCellValue('B' .$i,$row['Name']);
$objPHPExcel->getActiveSheet()->setCellValue('C' .$i,$row['score']);
$i++;
}
Can anyone help me get the desired output.
How to format a cell bold:
$styleArray = array('font' => array('bold' => true));
$objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
You can insert a new Row after inserting the class name.
if($row['class']!=$check)
{
$objPHPExcel->getActiveSheet()->setCellValue('A'.$i,$row['Class']);
$check=$row['class'];
// Merge the cells with the class name
$objPHPExcel->getActiveSheet()->mergeCells('A'.$i.':B'.$i);
$i++; // Next Row
}
Then you can put the name and score into column A and B:
$objPHPExcel->getActiveSheet()->setCellValue('A' .$i,$row['Name']);
$objPHPExcel->getActiveSheet()->setCellValue('B' .$i,$row['score']);
That should do all the trick. For further questions using PHPEXCEL youre able to contact me via email.
By the way, poor Simon :(
I use PHPExcel to import Excel files to my site. For example, there is two cells, A1 and A2, both merged. Is there a way to to find out is A1 merged to another cell (A2 or other) or not?
$workbook = new PHPExcel;
$sheet = $workbook->getActiveSheet();
$sheet->mergeCells('A1:E1');
$cell = $sheet->getCell('A1');
// Check if cell is merged
foreach ($sheet->getMergeCells() as $cells) {
if ($cell->isInRange($cells)) {
echo 'Cell is merged!'
break;
}
}
I think there isn't better solution because of the way phpexcel stores information about merged cells.
The easiest way is to use the getMergeRange() method.
if ($cell->getMergeRange()) {
// cell is merged
}
I suspect many people will want to know the value of the merged cell, in which case you can refer to the following code:
if (($range = $cell->getMergeRange()) && !$cell->isMergeRangeValueCell()) {
$first_in_range_coordinates = strtok($range, ':');
$value = $sheet->getCell($first_in_range_coordinates)->getValue();
}