I was thinking since i can import the data from excel to my database, is it possible to upload the excel file itself and be able to display it in your website?
For client webpage side, use html form <input type="file"> to upload excel file from browser to PHP file.
Example upload-submit.html:
<form action="upload.php">
<input type="file" name="excel-upload" />
<input type="submit" />
</form>
In your PHP upload script you will need to include the PHPExcel library (https://github.com/PHPOffice/PHPExcel) to read and parse the uploaded Excel file. You can read Mark Baker's very good example on how to read from Excel and insert into a database: how to use phpexcel to read data and insert into database?
Example upload.php :
// Include PHPExcel_IOFactory
include 'PHPExcel/IOFactory.php';
// Move the uploaded file from temporary server directory into an 'uploads' directory
$fileName = basename($_FILES["excel-upload"]["name"]);
$uploadedExcelFullPath = __DIR__.'/uploads/'.$fileName;
move_uploaded_file($_FILES['excel-upload']['tmp_name'],$uploadedExcelFullPath);
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($uploadedExcelFullPath);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($uploadedExcelFullPath);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($uploadedExcelFullPath,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// Insert row data array into your database here
// You can also format data into HTML table row format and echo out here
var_dump($rowData);
}
Related
I am creating excel file with single worksheet using PHPExcel.
I have managed to do this but the issue came after when I created it ones then it didn't get clear so when I am creating it again the the previous data came along with the new data.
So I am just want to clear the excel file before using it again.
Here is the code:
require_once APPPATH.'third_party/PHPExcel.php';
require_once APPPATH.'third_party/PHPExcel/IOFactory.php';
//Getting Data form database
$bTob_gstdata = $this->reports_model->get_bTob_gstdata($date_from, $date_to);
//Sample Excel File (which is clear already Just contain the structure)
$filename = 'assets/btob_base_excel.xls';
$objPHPExcel = PHPExcel_IOFactory::load($filename);
echo $filetype = PHPExcel_IOFactory::identify($filename);
$excel2 = PHPExcel_IOFactory::createReader($filetype);
$excel2 = $excel2->load('assets/btob_base_excel.xls'); // Empty Sheet
$excel2->setActiveSheetIndex(0);
$t=0;
$total_invoice_count = 0;
$recipients_count = array();
$invoice_count = array();
for($k=5;$k<(count($bTob_gstdata)+5);$k++)
{
//Adding Data in Excel WorkSheet
$excel2->getActiveSheet()
->setCellValue('A'.$k, $bTob_gstdata[$t]["dist_gstin"]);
$t++;
}
$excel2->getActiveSheet()->setCellValue('A3', (count($recipients_count)));
$excel2->getActiveSheet()->setCellValue('B3', (count($invoice_count)));
$excel2->getActiveSheet()->setCellValue('D3', '=SUM(D5:D'.(count($bTob_gstdata)+5).')');
$excel2->getActiveSheet()->setCellValue('J3', '=SUM(J5:J'.(count($bTob_gstdata)+5).')');
$excel2->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($excel2, $filetype);
$objWriter->save('btocl_gst_report.xls'); //Saving the excel file
header("location:".base_url("btob_gst_report.xls")); // Downloading the excel file
I want to clear the created excel file to Reuse
I have a problem converting file feom CSV to XLSX format:
Index.php
<?php
if (!isset($_FILES["file"]))
{
?>
<html>
<body>
<h1>Convert CSV to XLSX</h1>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</form>
</body>
</html>
<?php
exit;
}
//obtain PHPExcel from http://phpexcel.codeplex.com
require_once('Classes\PHPExcel.php');
require_once('CSVToExcelConverter.php');
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"];
exit;
}
try
{
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename='.'example.xlsx');
CSVToExcelConverter::convert($_FILES['file']['tmp_name'], 'php://output');
} catch(Exception $e) {
echo $e->getMessage();
}
CSVToExcelConverter.php
class CSVToExcelConverter
{
/**
* Read given csv file and write all rows to given xls file
*
* #param string $csv_file Resource path of the csv file
* #param string $xls_file Resource path of the excel file
* #param string $csv_enc Encoding of the csv file, use utf8 if null
* #throws Exception
*/
public static function convert($csv_file, $xls_file, $csv_enc=null) {
//set cache
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
//open csv file
$objReader = new PHPExcel_Reader_CSV();
if ($csv_enc != null)
$objReader->setInputEncoding($csv_enc);
$objPHPExcel = $objReader->load($csv_file);
$in_sheet = $objPHPExcel->getActiveSheet();
//open excel file
$objPHPExcel = new PHPExcel();
$out_sheet = $objPHPExcel->getActiveSheet();
//row index start from 1
$row_index = 0;
foreach ($in_sheet->getRowIterator() as $row) {
$row_index++;
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false);
//column index start from 0
$column_index = -1;
foreach ($cellIterator as $cell) {
$column_index++;
$out_sheet->setCellValueByColumnAndRow($column_index, $row_index, $cell->getValue());
}
}
//write excel file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save($xls_file);
}
}
CSV File format: CSV file opened with Excel
xlsx file I get after conversion
Basicaly I would like to get output similar to original csv file, but in xmlx format, how to do that?
The "default" separator for reading a CSV file in PHPExcel is a comma (,). Your CSV file is using something other than a comma - perhaps a tab ("\t"), which is also commonly used for such files).
If the values isn't a comma (and we can't tell from an image of the file viewed in MS Excel) then you have to tell PHPExcel explicitly what that separator is before loading.
e.g.
$objReader->setDelimiter("\t");
I'm trying to upload a spreadsheet and read it into a MySQL database using PHPExcel.
For .xlsx files it works fine but whenever I try to upload a .ods file it throws the error: PHP Fatal error: Call to a member function getNamespaces() on a non-object in PHPExcel_1.7.9/Classes/PHPExcel/Reader/OOCalc.php on line 341
What's going wrong?
HTML Form:
<form method="post" enctype="multipart/form-data">
Upload File: <input type="file" name="spreadsheet"/>
<input type="submit" name="submit" value="Submit" />
</form>
PHP (In same file):
//Check valid spreadsheet has been uploaded
if(isset($_FILES['spreadsheet'])){
if($_FILES['spreadsheet']['name']){
if(!$_FILES['spreadsheet']['error'])
{
$inputFile = $_FILES['spreadsheet']['name'];
$extension = strtoupper(pathinfo($inputFile, PATHINFO_EXTENSION));
if($extension == 'XLSX' || $extension == 'ODS'){
//Read spreadsheeet workbook
try {
$inputFile = $_FILES['spreadsheet']['tmp_name'];
$inputFileType = PHPExcel_IOFactory::identify($inputFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFile);
} catch(Exception $e) {
die($e->getMessage());
}
//Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
//Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
//Insert into database
}
}
else{
echo "Please upload an XLSX or ODS file";
}
}
else{
echo $_FILES['spreadsheet']['error'];
}
}
}
?>
When a file is uploaded to your webserver, The file will be saved in the temporary folder of your system with a random name.
What you were trying to do was giving the actual name of the file you uploaded, But since the file was created with a random name in the tmp folder.
You will need to use tmp_name instead, Which actually point the that random named file.
Also note, in name You only have the name of the file that was uploaded and not the path,
But with tmp_name you have the actual path to the file.
See the following example of a file upload you would get.
array(
[UploadFieldName]=>array(
[name] => MyFile.jpg
[type] => image/jpeg
[tmp_name] => /tmp/php/php6hst32
[error] => UPLOAD_ERR_OK
[size] => 98174
)
)
change your code to this instead
//Check valid spreadsheet has been uploaded
if(isset($_FILES['spreadsheet'])){
if($_FILES['spreadsheet']['tmp_name']){
if(!$_FILES['spreadsheet']['error'])
{
$inputFile = $_FILES['spreadsheet']['tmp_name'];
$extension = strtoupper(pathinfo($inputFile, PATHINFO_EXTENSION));
if($extension == 'XLSX' || $extension == 'ODS'){
//Read spreadsheeet workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFile);
} catch(Exception $e) {
die($e->getMessage());
}
//Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
//Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
//Insert into database
}
}
else{
echo "Please upload an XLSX or ODS file";
}
}
else{
echo $_FILES['spreadsheet']['error'];
}
}
}
?>
In my case there was an error detecting the extension in this line
$extension = strtoupper(pathinfo($inputFile, PATHINFO_EXTENSION));
if you need to solve just check from the name parameter
$extension = strtoupper(explode(".", $_FILES['spreadsheet']['name'])[1]);
The rest is working thanks :)
Trying to allow the user to select a browsed excel file from their computer. Take that excel file and parse through it then write the data to a database. I am having trouble getting the parse to work. I know I need to use...
<form enctype="multipart/form-data" action="uploader.php" method="POST">
Choose a file to upload: <input name="uploadedfile" type="file" id="uploadedfile" /> <br />
<input type="submit" value="Upload File" />
and my only question is that when I use the $_FILES["uploadedfile"]["name"] it only gives me the filename and not the directory of the file so how can I pass this to PHPExcel Reader. Isn't this just a string of the filename and not actually a file path?
Heres what I have in my uploader.php:
<?php
include ('/PHPExcel/Classes/PHPExcel/IOFactory.php');
$filename = $_FILES["uploadedfile"]['name'];
echo $filename;
$inputFileType = PHPExcel_IOFactory::identify($filename);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader -> load($filename);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$data = array();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
$data[] = $rowdata;
// Insert row data array into your database of choice here
}
foreach ($data as $param){
echo $param;
}
?>
You'll need the temporary name to either read it or move it to a place of your choosing:
print_r($_FILES);
Point the path directly and pass it to IOFactory:
$filename = $_FILES["uploadedfile"]['name'];
$fullFilename = PROJECT_DIR . 'upload/' . $filename;
$inputFileType = PHPExcel_IOFactory::identify($fullFilename);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader -> load($fullFilename);
iam trying to read an Excel File with PHP Reader, i print the information with an echo of the Highest Row and the Highest Colum, but what i get is the last formatted Column&Row and what i need is just the last cell where data was inserted. Here is my code:
require_once '..\..\..\Common\PHPExcel_1.7.9_doc\Classes\PHPExcel\IOFactory.php';
**code code code**
ReadExcelFile();
function ReadExcelFile(){
$inputFileType = 'Excel2007';
$inputFileName = '../ExcelFiles/test.xlsx';
$sheetname = 'Tabelle1';
try {
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(true);
$objReader->setLoadSheetsOnly($sheetname);
$objPHPExcel = $objReader->load($inputFileName);
}
catch(Exception $e) {
die('Error loading Excel file '.$e->getMessage());
}
$sheet = $objPHPExcel->getSheet(0);
echo $highestRow = $sheet->getHighestRow();
echo $highestColumn = $sheet->getHighestColumn();
}
Iam reading a very extense Macro that is modified once in a while externally (thats why i need to read just only to the last cell where has data) What i did was just a small copy of this excel file and the output was just
"254J"
But my last cell with data is about "210J". Anyone knows how to do it?
$highestRow = $sheet->getHighestDataRow();
$highestColumn = $sheet->getHighestDataColumn();