简体   繁体   English

我可以使用php覆盖excel文件吗?

[英]can i overwrite an excel file using php?

I created the file using PHPExcel at say C:\\path\\goes\\here\\filename.xls When I try to access it using header(), it creates a file filename(1) , filename(2) and so on.我在C:\\path\\goes\\here\\filename.xls使用PHPExcel创建了文件 当我尝试使用header(),访问它时header(),它会创建一个文件filename(1)filename(2)等等。 (PS : When i say overwrite, I mean to erase previous content and add new data). (PS:当我说覆盖时,我的意思是删除以前的内容并添加新数据)。

<?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";
}
?>

嗨,使用这个在header函数中写入您的filename

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

you can use php basename() function to get the file names at that specific path and then check if the file you are creating already exists.您可以使用 php basename() 函数获取该特定路径的文件名,然后检查您正在创建的文件是否已经存在。 if it already exists then delete the old file and create the new file.如果它已经存在,则删除旧文件并创建新文件。 https://www.w3schools.com/php/func_filesystem_basename.asp https://www.w3schools.com/php/func_filesystem_basename.asp

and this should be done before you call header("Content-Disposition: attachment; filename=$filename");这应该在你调用 header("Content-Disposition: attachment; filename=$filename"); 之前完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM