[英]can i overwrite an excel file using php?
我在C:\\path\\goes\\here\\filename.xls
使用PHPExcel
創建了文件 當我嘗試使用header(),
訪問它時header(),
它會創建一個文件filename(1)
、 filename(2)
等等。 (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"');
您可以使用 php basename() 函數獲取該特定路徑的文件名,然后檢查您正在創建的文件是否已經存在。 如果它已經存在,則刪除舊文件並創建新文件。 https://www.w3schools.com/php/func_filesystem_basename.asp
這應該在你調用 header("Content-Disposition: attachment; filename=$filename"); 之前完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.