2016-07-08 44 views
0

我使用PHPExcel创建了文件C:\path\goes\here\filename.xls 当我尝试使用header(),访问它时,它创建了一个文件filename(1),filename(2)等等。 (PS:当我说覆盖,我的意思是擦除以前的内容并添加新的数据)。我可以用php覆盖excel文件吗?

<?php 

include 'PHPExcel.php'; 

require_once ("C:\\xampp\\htdocs\\excel_mailer_2\\PHPMailer-master\\class.phpmailer.php"); 

$path   = "C:\\Users\\Manish\\Downloads"; 
$file_name  = $_GET['file_name']; 

$DB_server  = "localhost"; 
$DB_username = "root"; 
$DB_password = ""; 
$DB_dbname  = "timetracker"; 
$DB_tablename = "tt_users"; 

$conn   = mysqli_connect ($DB_server, $DB_username, $DB_password, $DB_dbname); 

if (mysqli_connect_errno()) { 
    die ("Connection Failed!"); 
} 

$sql = "SELECT *"; 
$sql .= " FROM $DB_tablename"; 

if ($result = mysqli_query($conn,$sql)); 

else die("Couldn't execute query:<br />" . mysqli_error(). "<br />" . mysqli_errno()); 

$file_ending = ".xls"; 

$filename = $file_name.$file_ending; 

//header("Content-Type: application/vnd.ms-excel"); 
header("Content-Disposition: attachment; filename=$filename"); 



/*******Start of Formatting for Excel*******/ 

$sep  = "\t"; 
$flag  = true; 
$col_names = ""; 

while($row = mysqli_fetch_assoc($result)) { 
    $data_insert = ""; 
      foreach($row as $field=>$data) { 
     if ($flag) 
      $col_names  .= $field.$sep; 
     if(!isset($data)) 
      $data_insert .= "NULL".$sep; 
     elseif ($data != "") 
      $data_insert .= $data.$sep; 
     else 
      $data_insert .= "".$sep; 
    } 

    if ($flag) { 
     $flag  = !$flag; 
     $col_names .= "\t"; 
     echo (trim($col_names)); 
     echo "\n"; 
    } 
    $data_insert .= "\t"; 
    echo (trim($data_insert)); 
    echo "\n"; 
} 
?> 
+0

没有与PHPExcel或PHP做写你filenameheader功能,这是浏览器的行为 –

+0

@马克·贝克,所以你说这是不可能的? –

+0

我在说,如果你发送一个文件到浏览器,那么它取决于浏览器本身,或客户端用户来确定文件将被保存为什么名称,并且服务器端代码只能“建议”一个文件名 –

回答

0

喜用这个

header('Content-Disposition: attachment; filename="filename.xls"'); 
+0

我做到了。编辑我的问题,并分享我的代码 –

+0

你试过看看$ file_name有什么? – user1234

+0

我通过'index.php'中的'$ file_name'发送了所需的文件名。 –

相关问题