[0] => stdClass Object
            [Votos_Balanceados] => 1
            [id] => 521691
            [titulo] => Converter Planilha Excel em MySQL
            [dataCadastro] => DateTime Object
                    [date] => 2015-06-01 23:07:36
                    [timezone_type] => 3
                    [timezone] => America/Sao_Paulo

            [isFirstPost] => -1
            [idUsuario] => 401063
            [status] => A
            [isExample] => 
            [NomeUsuario] => Eber
            [Apelido] => 
            [Foto] => 
            [Conteudo] => Tem alguns softwares que fazem esse processo de maneira bem fácil, como o dbconvert, fullconvert, fullcopyconvert. Segue os links. 


[][/url] ) )

Converter Planilha Excel em MySQL

Edson Pereira
   - 19 ago 2013

Preciso desenvolver um sistema onde o usuário upa uma planilha do excel para substituir uma tabela de preços no MySQL. Alguém tem alguma ideia de como poderia fazer isso ou por onde começar a pesquisar sobre o assunto. Desde já, obrigado.
Edson Rodrigues

Post mais votado

   - 01 jun 2015

Tem alguns softwares que fazem esse processo de maneira bem fácil, como o dbconvert, fullconvert, fullcopyconvert. Segue os links.

Emanoel Deivison
   - 19 ago 2013

Você poderia utilizar o fullconverter para tal tarefa, mas é pago!!!

Existe uma outra ferramenta que faz de forma gratuita!

Além dessas ferramentas você pode utilizar os script´s para converter diretamente:
/* Code at
/* Edit the entries below to reflect the appropriate values
$databasehost = "localhost";
$databasename = "test";
$databasetable = "sample";
$databaseusername ="test";
$databasepassword = "";
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "E:\Webcache\AA ONLINE\test1\english1.csv";
/* Would you like to add an ampty field at the beginning of these records?
/* This is useful if you have a table with the first field being an auto_increment integer
/* and the csv file does not have such as empty field before the records.
/* Set 1 for yes and 0 for no. ATTENTION: don't set to 1 if you are not sure.
/* This can dump data in the wrong fields if this extra field does not exist in the table
$addauto = 0;
/* Would you like to save the mysql queries in a file? If yes set $save to 1.
/* Permission on the file should be set to 777. Either upload a sample file through ftp and
/* change the permissions, or execute at the prompt: touch output.sql && chmod 777 output.sql
$save = 1;
$outputfile = "output.sql";
if(!file_exists($csvfile)) {
echo "File not found. Make sure you specified the correct path.\n";
$file = fopen($csvfile,"r");
if(!$file) {
echo "Error opening data file.\n";
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
$csvcontent = fread($file,$size);
$con = @mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
@mysql_select_db($databasename) or die(mysql_error());
$lines = 0;
$queries = "";
$linearray = array();
foreach(split($lineseparator,$csvcontent) as $line) {
$line = trim($line," \t");

$line = str_replace("\r","",$line);

This line escapes the special character. remove it if entries are already escaped in the csv file
$line = str_replace("'","\'",$line);

$linearray = explode($fieldseparator,$line);

$linemysql = implode("','",$linearray);

$query = "insert into $databasetable values('','$linemysql');";
$query = "insert into $databasetable values('$linemysql');";

$queries .= $query . "\n";
if($save) {

if(!is_writable($outputfile)) {
echo "File is not writable, check permissions.\n";

else {
$file2 = fopen($outputfile,"w");

if(!$file2) {
echo "Error writing to the output file.\n";
else {

echo "Found a total of $lines records in this csv file.\n";



Dá uma olhada nesses link´s também:!topic/phpmg/ldDS_-P1VeM


Exemplo prático:


Outro exemplo:

--Dynamic Excel or Word File from MySQL--
php-doc-xls-gen for php/MySQL: (.doc or .xls dumper):

This script takes the contents of a MySQL table and dumps it to
either a dynamically-generated MS Word File (file with ending '.doc')
or a dynamically-generated MS Excel File (file with ending '.xls').

Prerequisites: You Must have MS Word and/or MS Excel installed on
the same computer as your web browser for this to work (although
the script can be placed on any Unix/Linux server, you have to access it using
a browser on a Windows machine with either Word or Excel installed).

How to use:
1)edit the MySQL Connection Info below for your MySQL connection
& for the name of the MySQL table that you would like to make the dump for
2)save this file somewhere on your server
3)link to this file from another page:
a)for Word dumps:
<a href="this_file_name.php?w=1">link to word dump</a>
b)for Excel dumps:
<a href="this_file_name.php">link to excel dump</a>
--or else--
create a Bookmark to this page (include any of the optional parameters
described below as part of the query string for the bookmarked URL)
4)how to reuse this code to create a dump for ANY MySQL table on your server:
a)comment-out this line below under MySQL Connection Info:
//$DB_TBLName = "your_table_name";
b)include the name of your MySQL table in links (or bookmarks) to this page
as an extra parameter:
ie: for word dump--
<a href="this_file_name.php?w=1&DB_TBLName=your_table_name">link to word dump</a>
ie: for excel dump--
<a href="this_file_name.php?DB_TBLName=your_table_name">link to excel dump</a>
c)all of the above also holds true for the name of the Database:
you could pass along the name of the Database as a parameter to this script
in order to use it on many different databases on your server:
comment out //$DB_DBName = "your database"; in this script below
and then link to this file like:
5)if you're resourceful, you could also pass the sql statement to be used for this
script as a parameter: "this_file_name.php?sql=..."
but you might have to URL-ENCODE your sql statement before passing it to this script,
and then URL-DECODE it in the beginning of this script for it to work.

To change the formatting of the Word or Excel File generated:
change the respective parts of the coding for the word or the excel file that format
the database info sent to the browser. Most useful for this are the escape characters
for tabs ('\t') & line returns ('\n'). Experiment with these until you get the formatting
that you desire.

If you're going to be using this script with SSL, please see the comments marked

This code is freeware (GPL). Please feel free to do with it what you'd like.
Comments, bugs, fixes to:

Originally: Nov. 25th, 2001
Updated: May 12th, 2002
Updated: July 1st, 2002
Updated: Jan 19th, 2003 - SSL Fix for MSIE

Thanks to Josue & Steven d.B. for helping point out
improvements for this code!

//EDIT YOUR MySQL Connection Info:
$DB_Server = "localhost"; //your MySQL Server
$DB_Username = ""; //your MySQL User Name
$DB_Password = ""; //your MySQL Password
$DB_DBName = ""; //your MySQL Database Name

// get the right table/year
if(substr($table, 0, 3) == "ev_"){$table = "$ev_year";}
if(substr($table, 0, 3) == "jn_"){$table = "$jrn_year";}
if(substr($table, 0, 3) == "cs_"){$table = "$cs_year";}

$DB_TBLName = "$table"; //your MySQL Table Name

//$DB_TBLName, $DB_DBName, may also be commented out & passed to the browser
//as parameters in a query string, so that this code may be easily reused for
//any MySQL table or any MySQL database on your server

//you can use just about ANY kind of select statement you want -
//edit this to suit your needs!

// switch column name if exporting the 'pm_post' table.
if ($table == "pm_post"){
$userkey = "groupname";
$userkey = "uemail";

// if column name exists, export it
if ($table != ""){

$DB_TBLName = "$table";
$sql = "Select * from $DB_TBLName WHERE $userkey = '$userkey'";
$DB_TBLName = "$trk";
$sql = "Select * from $DB_TBLName";


//Optional: print out title to top of Excel or Word file with Timestamp
//for when file was generated:
//set $Use_Titel = 1 to generate title, 0 not to use title
$Use_Title = 1;
//define date for title: EDIT this to create the time-format you need
$now_date = date('m-d-Y H:i');
//define title for .doc or .xls file: EDIT this if you want
$title = "Data from the '$ttype' for account #$userID. Exported from the XXXXXXXXXXXXX System on $now_date";

Leave the connection info below as it is:
just edit the above.

(Editing of code past this point recommended only for advanced users.)
//create MySQL connection
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password)
or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = @mysql_select_db($DB_DBName, $Connect)
or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = @mysql_query($sql,$Connect)
or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());

//if this parameter is included ($w=1), file returned will be in word format ('.doc')
//if parameter is not included, file returned will be in excel format ('.xls')
if (isset($w) && ($w==1)){
$file_type = "msword";
$file_ending = "doc";
else {
$file_type = "";
$file_ending = "xls";
//header info for browser: determines file type ('.doc' or '.xls')
header("Content-Type: application/$file_type");
header("Content-Disposition: attachment; filename=$ttype.$file_ending");
header("Pragma: no-cache");
header("Expires: 0");

To get this script to work properly in MSIE,
do the following:

//delete this header:
header("Pragma: no-cache");

//and add these headers just after the "Expires: 0" header:
header("Keep-Alive: timeout=15, max=100");
header("Connection: Keep-Alive");
header("Transfer-Encoding: chunked");

Thanks to Christopher Owens for this!

/* Start of Formatting for Word or Excel */

if (isset($w) && ($w==1)) //check for $w again
//create title with timestamp:
if ($Use_Title == 1){
//define separator (defines columns in excel & tabs in word)
$sep = "\n"; //new line character

while($row = mysql_fetch_row($result))
//set_time_limit(60); // HaRa
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result);$j++)
//define field names
$field_name = mysql_field_name($result,$j);
//will show name of fields
$schema_insert .= "$field_name:\t";
if(!isset($row[$j])) {
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "") {
$schema_insert .= "$row[$j]".$sep;
else {
$schema_insert .= "".$sep;
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert .= "\t";
//end of each mysql row
//creates line to separate data from each MySQL table row
print "\n----------------------------------------------------\n";
//create title with timestamp:
if ($Use_Title == 1){
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character

//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
//end of printing column names

//start while loop to get data
note: the following while-loop was taken from phpMyAdmin 2.1.0.
--from the file "".
while($row = mysql_fetch_row($result))
//set_time_limit(60); // HaRa
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result);$j++)
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
$schema_insert .= "".$sep;
$schema_insert = str_replace($sep."$", "", $schema_insert);
//following fix suggested by Josue (thanks, Josue!)
//this corrects output in excel when table fields contain \n or \r
//these two characters are now replaced with a space
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print "\n";

Abração e bons códigos!!

Espero te ajudado!!!

Marcio Araujo
   - 19 ago 2013

não sabia que fosse possivel pegar dados do excel e colocar em algum sgbd. interessante.

William (devwilliam)
   - 20 ago 2013

Colega de uma olhada nessa biblioteca, uso ela com frequência em sistemas onde é necessário fazer importações de planilha.

Você pode criar uma classe e adaptar algumas validações, fica muito bom.

Edson Pereira
   - 21 ago 2013

Estou tentando alimentar uma tabela no MySQL com um arquivo .csv. Quando eu executo o SQL direto no phpMyAdmin o comando funciona:

LOAD DATA INFILE 'C:\\xampp\\htdocs\\Testes\\csv\\carros.csv' REPLACE INTO TABLE carros FIELDS TERMINATED BY ';' ENCLOSED BY '\"' ESCAPED BY '\\'

Porém quando tento executar via programação, dá erro de SQL:
$planilha = "'C:\\xampp\\htdocs\\Testes\\csv\\carros.csv'";
if (isset($_POST["gravar"])) {
$gravar = mysql_query("LOAD DATA INFILE $planilha
") or die(mysql_error());
if ($gravar == '1') {
echo "Sucesso";
} else {
echo "Erro";
[/ [tagcod]
Erro do SQL:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''\'' at line 2

Alguém saberia me dizer qual p problema? Já tentei tudo que eu sabia e nada.
Desde já, agradeço...