PHP import Excel into database (xls & xlsx) - php

I tried to search for some plugins to import Excel file into MySQL database, one of them is http://code.google.com/p/php-excel-reader/
The tool is so powerful that it displays the entire excel content into html.
However, I think I just need to read the Excel file and extract the contents, for example, into an array, and then write a SQL statement for entering into the database.
Would there be any good codes and packages? Thanks!

This is best plugin with proper documentation and examples
https://github.com/PHPOffice/PHPExcel
Plus point: you can ask for help in its discussion forum and you will get response within a day from the author itself, really impressive.

Sometimes I need to import large xlsx files into database, so I use spreadsheet-reader as it can read file per-row. It is very memory-efficient way to import.
<?php
// If you need to parse XLS files, include php-excel-reader
require('php-excel-reader/excel_reader2.php');
require('SpreadsheetReader.php');
$Reader = new SpreadsheetReader('example.xlsx');
// insert every row just after reading it
foreach ($Reader as $row)
{
$db->insert($row);
}
?>
https://github.com/nuovo/spreadsheet-reader

If you can convert .xls to .csv before processing, you can use the query below to import the csv to the database:
load data local infile 'FILE.CSV' into table TABLENAME fields terminated by ',' enclosed by '"' lines terminated by '\n' (FIELD1,FIELD2,FIELD3)

If you save the excel file as a CSV file then you can import it into a mysql database using tools such as PHPMyAdmin
Im not sure if this would help in your situation, but a csv file either manually or programatically would be a lot easier to parse into a database than an excel file I would have thought.
EDIT: I would however suggest looking at the other answers rather than mine since #diEcho answer seems more appropriate.

I wrote an inherited class:
<?php
class ExcelReader extends Spreadsheet_Excel_Reader {
function GetInArray($sheet=0) {
$result = array();
for($row=1; $row<=$this->rowcount($sheet); $row++) {
for($col=1;$col<=$this->colcount($sheet);$col++) {
if(!$this->sheets[$sheet]['cellsInfo'][$row][$col]['dontprint']) {
$val = $this->val($row,$col,$sheet);
$result[$row][$col] = $val;
}
}
}
return $result;
}
}
?>
So I can do this:
<?php
$data = new ExcelReader("any_excel_file.xls");
print_r($data->GetInArray());
?>

You can use PHPOFFICE as "diEcho" said. And then use bin2hex() function to insert data to database (SQL SERVER or MySQL) as a BLOB data type.
bin2hex() function helped me alot.

Related

edit existing excel on web page using php

Does anyone have an idea to create the dynamic form with uploaded excel file.
We need to facilitate users to add data in the pre-uploaded file. Can anyone help with this? We are doing in this way:
$objPHPExcelWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'HTML');
$objPHPExcelWriter->save('php://output');
But this above code only displays structure of excel on the web still we're unable to edit it.
you will need 2 pear packages
PHP-ExcelReader package
Spreadsheet_Excel_Writer package
What you need to do is read first the excel file use PHP-ExcelReader package It reads the binary format of XLS files directly and can return values and formats from any cell. http://code.google.com/p/php-excel-reader/
read the excel file
$data = new Spreadsheet_Excel_Reader("test.xls");
show the data of the file
$data->dump($row_numbers=false,$col_letters=false,$sheet=0,$table_class='excel')
Once you have stored the data in a variable save the data in another file this time you will use the The Spreadsheet_Excel_Writer package https://github.com/pear/Spreadsheet_Excel_Writer
<?php
require_once 'Spreadsheet/Excel/Writer.php';
$workbook = new Spreadsheet_Excel_Writer('test.xls');
$worksheet =& $workbook->addWorksheet('My first worksheet');
if (PEAR::isError($worksheet)) {
die($worksheet->getMessage());
}
$workbook->close();
?>

Xlsx file, Read all spreadsheet in php

I am using simplexlsx to read xlsx sheet,
I have multiple tabs in my xlsx file, When I am trying to read data, its shows data only for first tab,
for better understanding i have attach print screen.
Try This,
$this->load->library('simplexlsx');
$xlsx = new SimpleXLSX( $file_path );
$data['csv_data'] = $xlsx->rows();
It is because when you select something from an excel file it performs that action with the active sheet which is by default is the first one.
You need to change that to the required sheet
Use the following code to do that
$objPHPExcel->setActiveSheetIndex($count); // Use no of the sheet you want to select -1 as count

how to format exported excel sheet with column color in php?

i have export a excel sheet which will collect data from my customer table (Mysql database) now i want to format it with column color.
here is my code to export excel sheet....
<?php
ob_start();
session_start();
include("include/session.php");
include("common_function.php");
//connect the database
$customer_id=$_GET['pid'];
//Enter the headings of the excel columns
$contents="Sr.,Agent Name,Contact Person,Contact Number,Password,Deal With Customer,References,Time to reach,Package Offered,Mode of Payment,Note,NEAREST CROSS STREET,DATE OF BIRTH\n";
//Mysql query to get records from datanbase
//You can customize the query to filter from particular date and month etc...Which will depends your database structure.
$sql = "SELECT id,agent_id,fname1,mobile_no,password,fname,rentfrom,cheque_no,package_id,monthly_monitoring,final_comment,cross_street,dob1 FROM customer WHERE `id`='$customer_id'";
$user_query = mysql_query($sql);
//While loop to fetch the records
while($row = mysql_fetch_array($user_query))
{
$contents.=$row['id'].",";
$contents.=$row['agent_id'].",";
$contents.=$row['fname1'].",";
$contents.=$row['mobile_no'].",";
$contents.=$row['password'].",";
$contents.=$row['fname'].",";
$contents.=$row['rentfrom'].",";
$contents.=$row['cheque_no'].",";
$contents.=$row['package_id'].",";
$contents.=$row['monthly_monitoring'].",";
$contents.=$row['final_comment'].",";
$contents.=$row['cross_street'].",";
$contents.=$row['dob1']."\n";
}
// remove html and php tags etc.
$contents = strip_tags($contents);
//header to make force download the file
header("Content-Disposition: attachment; filename=Sale_report".date('d-m-Y').".csv");
print $contents;
?>
now i want to color my first row...
Heay Cnik,
Ayyappan Sekar is right.
PHPExcel is a library that can be used to generate xls( and many other formats ) file. Its purpose is to generate a file and not sending it on some id.
What you can do is, first generate a file using PHPExcel library and save it somewhere.
For sending email to some id, you can use http://php.net/manual/en/function.mail.php'>mail function. However, its little complex to send emails with attachments using php's mail function though not very difficult.
Refer the links given below:
1] http://www.shotdev.com/php/php-mail/php-send-email-upload-form-attachment-file/
2] Attach File Through PHP Mail (refer to the answer of asprin)
3] http://www.texelate.co.uk/blog/send-email-attachment-with-php/
The CSV file is a simple text file, you can't format it with color
http://en.wikipedia.org/wiki/Comma-separated_values
Hi instead of using header to export to excel, U can use PHPExcel library. It provides much easier inbuilt methods to achieve what u want.. even u can apply styles, merge cells etc

Excel validation using php

I have an excel sheet that is loaded with a dynamic result set of data.I need to validate the excel sheet before insert into mysql table.Validation such as Is there any duplicate entry,email validation etc.Any idea about how can validate using php.
As easy as :
parse your excel using phpexcel for example
make an array with all entries.
use array_unique to discart duplicates
then validate email fields
How do you parse the xls itself? For me the most simple solution is to parse the whole xls into an array then validate that. You can easily check for duplicates then iterate through with one foreach and validate the remaining.
You can use COM functions under PHP
$excel = new COM("excel.application") or die("Unable to instanciate excel");
//Open your file
$excel->Workbooks->Open("files/test.xls");
$Workbook = $excel->Worksheets(1); //Select the wortksheet
foreach($Workbook = $excel->Worksheets as $Worksheet)
{
//Loop each page in the book
$Worksheet->Activate; //Activate Sheet 1
for($row=0;$row<=$Worksheet->rows;$row++)
{
$row_item = $Worksheet->rows[$row];
//Hmm, i forgot the rest but you can do that ;)
}
}
You will have to read more about it, as i have never used it to open Excel sheets.
http://www.php.net/manual/en/class.com.php

Open an excel file using COM and save it as .xml file

Im trying the following code:
<?php
$workbook = "D:\b2\\test.XLS";
$sheet = "Sheet1";
#Instantiate the spreadsheet component.
$ex = new COM("Excel.sheet") or Die ("Did not connect");
#Get the application name and version
print "Application name:{$ex->Application->value}<BR>" ;
print "Loaded version: {$ex->Application->version}<BR>";
#Open the workbook that we want to use.
$wkb = $ex->application->Workbooks->Open($workbook) or Die ("Did not open");
#Create a copy of the workbook, so the original workbook will be preserved.
$ex->Application->ActiveWorkbook->SaveAs("D:\b2\Ourtest.xml");
#$ex->Application->Visible = 1; #Uncomment to make Excel visible.
#Optionally, save the modified workbook
$ex->Application->ActiveWorkbook->SaveAs("D:\Ourtest.xml");
#Close all workbooks without questioning
$ex->application->ActiveWorkbook->Close("False");
unset ($ex);
?>
This actually works and creates the Ourtest.xml file. But im getting characters like:
ÐÏࡱá > þÿ þÿÿÿ
I have tried with SaveAs("D:\Ourtest.pdf") and it says the file has been corrupted or incorrectly decoded.
Can anyone help me please?Thanks
That is because you are saving it as Excel Format. Check the Excel documentation for how to save it as an XML document - it might be a separate paramter to SaveAs or a different method alltogether (Export*).
EDIT: It seems SaveAs is the right method to use. Check the msdn documentation here. You probably want to specify the second parameter FileFormat. Maybe setting it to the XlFileFormat.xlXMLSpreadsheet value?
Problem solved by using
$ex->Application->ActiveWorkbook->SaveAs("D:\Ourtest.xml",46);
46 is the value for xlXMLSpreadsheet
Thanks everyone

Categories