简体   繁体   中英

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. (PS : When i say overwrite, I mean to erase previous content and add new data).

<?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. if it already exists then delete the old file and create the new file. https://www.w3schools.com/php/func_filesystem_basename.asp

and this should be done before you call header("Content-Disposition: attachment; filename=$filename");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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