Javascript 如何使用PHP Excel将MYSQL数据导出到Excel
这可能是一个相当不寻常的问题,但我真的被困在这里了。我正在从MYSQL数据库读取数据,并使用Echo通过PHP将这些数据创建一个表。现在,我想进入下一步,将这些数据(表中的数据)导出到Excel文档中。我真的很喜欢PHPExcel的工作方式,它是多么简单,但我很难找到获取数据的最有效方法,并将其放入excel文档中。当然,我不想手动写出“A1”,“A1数据”一直到Z1000-明白我的意思吗?我相信我应该把每件事都循环一遍。现在,这里是问题变得棘手的地方;是否有某种方法(请记住,这需要通过PHP完成)逐个单元格地读取表(循环)并将值分配给数组,然后循环遍历数组,如A1、arr[0]等 我想我必须使用JavaScript逐个单元格地读取表中的单元格,但是如何将数据分配给数组,以便将其作为PHP脚本的一部分使用——因为PHPExcel是用PHP编写的Javascript 如何使用PHP Excel将MYSQL数据导出到Excel,javascript,php,export-to-excel,Javascript,Php,Export To Excel,这可能是一个相当不寻常的问题,但我真的被困在这里了。我正在从MYSQL数据库读取数据,并使用Echo通过PHP将这些数据创建一个表。现在,我想进入下一步,将这些数据(表中的数据)导出到Excel文档中。我真的很喜欢PHPExcel的工作方式,它是多么简单,但我很难找到获取数据的最有效方法,并将其放入excel文档中。当然,我不想手动写出“A1”,“A1数据”一直到Z1000-明白我的意思吗?我相信我应该把每件事都循环一遍。现在,这里是问题变得棘手的地方;是否有某种方法(请记住,这需要通过PHP完
这个问题对你们有意义吗?还是我在这里遗漏了很多信息?让我知道,我可以编辑这个问题,这样对你们大家都更有意义。我有一个建议。例如,如果有人按下导出按钮,您向PHP页面发出POST请求,并执行与从MySQL检索数据相同的查询。一个是你得到的数据集。您只需将它们循环并写入excel即可。在下面的代码中,
$dataset
是MySQL结果集
$objPHPExcel = new PHPExcel();
$index = 1;
foreach($dataset as $subscriber)
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A' . $index, $subscriber['Email']);
$index ++;
}
如果您允许用户修改屏幕输出表中的数据。假设表中有文本框,也需要将它们保存到excel文件中。然后将这些元素命名为数组。例如:
txtName[]
因此,一旦你得到了职位,你就可以通过编程来处理它。理想的解决方案是创建一个平台无关的“Excel”文件,该文件可以由任何电子表格程序或文本编辑器(不仅仅是Excel)打开。我指的是一个基本的CSV文件
幸运的是,不需要外部库:PHP有一些用于读取/写入CSV文件的内置函数。因此,将数据从数据库中取出并放入Excel可读的csv文件的步骤如下:
fputcsv
操作中写入csv,而是在内存中打开一个文件句柄来执行相同的操作。这样做的优点是速度也比写入磁盘快。要在内存中打开文件句柄以在fputcsv
调用中使用,请执行以下操作:
$tmp\u handle=fopen('php://temp","r+";代码>
这将向内存而不是文件系统打开文件句柄。请注意,一旦文件句柄达到filesize中的默认值2Mb,PHP将透明地将其切换到文件系统上的临时文件。您可以避免这种情况,并强制文件句柄仅保留在内存中,方法是使用:
$tmp_handle=fopen('php://memory","r+";;
然后,您将在对fputcsv
的调用中使用此句柄:
fputcsv($tmp\u handle,$fields)代码>
您可以了解有关php://memory
和php://temp
,请按
让浏览器认为它是CSV文件
生成数据后,要使浏览器确信页面实际上是csv文件,您需要做的最后一件事是随数据一起发送正确的HTTP内容类型标题:
// generate my csv data here
header('Content-type: text/csv');
header('Content-disposition: attachment;filename=MyVerySpecial.csv');
// reset the file handle's pointer to the beginning of the stream
rewind($tmp_handle);
// output the contents of the file handle to the browser
echo stream_get_contents($tmp_handle);
Simple:导出逗号分隔的文件。碰巧PHP有一个内置函数可以实现这一点:。。。Excel将立即打开它有任何不使用csv格式的原因吗?这样,您就不会局限于一个电子表格应用程序、较小的文件和用于处理数据的内置php函数。@rdlowrey无论哪种方式,我都需要以某种方式在表格中循环以检索将导出的值。因此,我的问题仍然是-如何做到这一点?@Evan(1)(2)在循环中,使用来编写csv文件。(3) 结束。如果你不能让它工作,带着你试过的代码回来问另一个问题。那根本就不是问题。这就是我要做的,谢谢。呵呵,这真的没必要。一个当之无愧的答案。剩下的唯一问题是,我似乎无法使用fopen将文件写入本地磁盘。我总是遇到这样的错误:“无法打开流:没有这样的文件或目录”,我使用的代码如下:$filename=trim(“C:/file.csv”)$fp=fopen($filename,'w');首先,你为什么要对一个你已经知道没有多余字符的字符串使用trim
?第二,虽然我从未在windows环境中使用过PHP,但我猜您的文件名应该是这样的:“C:\\file.csv”
(请注意有两个反斜杠——您需要一个额外的反斜杠来避开主反斜杠)我一直在做一些额外的预防措施,因为我已经做了一个多小时了。但是,使用上面的路径会在远程目录中创建一个名为C:\file.csv的文件。很奇怪,也许我误解了你的意思?fopen
调用将在执行php请求的服务器的文件系统上执行。如果该服务器不是您正在使用的计算机,它不会将其保存在本地,而是将其保存在远程服务器上。如果PHP进程正在执行o
<?php
//EDIT YOUR MySQL Connection Info:
$DB_Server = "localhost"; //your MySQL Server
$DB_Username = "root"; //your MySQL User Name
$DB_Password = ""; //your MySQL Password
$DB_DBName = "school"; //your MySQL Database Name
$DB_TBLName = "s_question"; //your MySQL Table Name
if(isset($_POST['exp_stdque'])) {
$exstdid = $_POST['expstd'];
//$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
//DEFINE SQL QUERY:
//edit this to suit your needs
$sql = "Select * from $DB_TBLName WHERE std_id = $exstdid";
//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 = "Dump For Table $DB_TBLName from Database $DB_DBName 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 = "vnd.ms-excel";
$file_ending = "xls";
}
//header info for browser: determines file type ('.doc' or '.xls')
HEADER("Content-Type: application/$file_type");
HEADER("Content-Disposition: attachment; filename=database_dump.$file_ending");
HEADER("Pragma: no-cache");
HEADER("Expires: 0");
/* Start of Formatting for Word or Excel */
IF (ISSET($w) && ($w==1)) //check for $w again
{
/* FORMATTING FOR WORD DOCUMENTS ('.doc') */
//create title with timestamp:
IF ($Use_Title == 1)
{
ECHO("$title\n\n");
}
//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";
PRINT(TRIM($schema_insert));
//end of each mysql row
//creates line to separate data from each MySQL table row
PRINT "\n----------------------------------------------------\n";
}
}ELSE{
/* FORMATTING FOR EXCEL DOCUMENTS ('.xls') */
//create title with timestamp:
IF ($Use_Title == 1)
{
ECHO("$title\n");
}
//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";
}
PRINT("\n");
//end of printing column names
//start while loop to get data
WHILE($row = MYSQL_FETCH_ROW($result))
{
//set_time_limit(60); // HaRa
$schema_insert = "";
FOR($j=0; $j<mysql_num_fields($result);$j++)
{
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);
//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(TRIM($schema_insert));
PRINT "\n";
}
}
}
?>