So, i have a form which able to read excel files and save to database by uploading an excel file. It is fine when i upload .xls file, but not with the .xlsx. Here is the code:
echo ' File berhasil diupload => '.$dok['file_name']; //success to echo uploaded .xlsx file
//EXCEL READING, load library
$this->load->library('excel');
//Identify the type of $inputFileName
$inputFileType = PHPExcel_IOFactory::identify(FCPATH."/asset/files/uploads/".$dok['file_name']);
//Create a new Reader of the type that has been identified
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
//Failed to echo (if i upload .xlsx file)
echo 'input file type => '.$inputFileType;
//begin to read excel file
$this->excel = $objReader->load(FCPATH."/asset/files/uploads/".$dok['file_name']);
$objWorksheet=$this->excel->getActiveSheet();
$highestRow=$objWorksheet->getHighestRow();
$highestColumm = $objWorksheet->getHighestColumn();
$highestColumm++;
//jika option timpa, maka delete semua data
if($timpa == 'y')
{
$this->_model->del_table_mcactivity();
}
//read per row and save to database
foreach($this->excel->getWorksheetIterator() as $worksheet){
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns= ord($highestColumn) - 64;
for ($row = 2; $row <= $highestRow; ++ $row) {
$kodemak = $objWorksheet->getCell("A$row")->getValue();
$tahun = $objWorksheet->getCell("B$row")->getValue();
$unitkerja = $objWorksheet->getCell("C$row")->getValue();
$nomorkegiatan = $objWorksheet->getCell("D$row")->getValue();
$kegiatan = $objWorksheet->getCell("E$row")->getValue();
$noskkegiatan = $objWorksheet->getCell("F$row")->getValue();
$jenis = $objWorksheet->getCell("G$row")->getValue();
$pagu = $objWorksheet->getCell("H$row")->getValue();
//get for refworkingunit id
$idrefworkingunit = $this->_model->get_workingunit_by_name($unitkerja);
//filtering for budget
$budget = $this->filter_budget($pagu);
//grouping variable to save in database
$activity_data = array('year'=>$tahun, 'idrefworkingunit'=>$idrefworkingunit, 'activitynumber'=>$nomorkegiatan, 'activityname'=>$kegiatan, 'activityreference'=>$noskkegiatan, 'accountnumber'=>$kodemak, 'traveltype'=>$jenis, 'budget'=> $budget);
//insert to database
$this->db->insert('mcactivity', $activity_data);
}
}
I use PHPExcel_IOFactory::identify() to identify the reader should be used. But i think it's failed.I've read this question , then i replace
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
with:
$objReader = PHPExcel_IOFactory::createReader('Excel2007'); but it still doesn't work. Can somebody help me, please ?
XLS and XLSX are two different files types.
XLS
$this->load->library('Excel5');
XLSX
$this->load->library('Excel2007');
Consult the documentation "PHPExcel User Documentation - Reading Spreadsheet Files.doc" that comes with PHPExcel. Page 1 explains the formats, and Page 4 explains different ways of telling PHPExcel what file type to handle.
There are multiple lines where the reference to "Excel2007" and "Excel5" might occur.
Do a search on 'Excel' and not over-look any possibility.
e.g. $objReader = new PHPExcel_Reader_Excel2007(); //was Excel5
Change to _Excel2007 did allow me to read a .xlsx file, but did not break a script that read a .xls file. So there might be backwards compatibility.
Related
I just started using PHPExcel yesterday. It works like a charm except when I use it to read xlsx file downloaded from internet. It is not able to read the file until I open the dowloaded file and save it explicitly without making any change.
$objPHPExcel = PHPExcel_IOFactory::load($inputFile);
Line I use to load the Excel file.
Where am I going wrong? Am I missing some code. Something else needs to be written along with the above line of code to load the file.
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for ($row = 1; $row <= $highestRow; ++ $row) {
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
if($col==0){
$val = \PHPExcel_Style_NumberFormat::toFormattedString($val, 'YYYY-MM-DD');
}
$dataArr[$row][$col] = $val;
}
This code is able to read the excel when I open the excel and save it.
I did a custom X++ code to import data from Excel to General Ledger, however the import works very well on the server directly but while running it from the end user(client) it imports several records (like 24 records) then throw an error
the number of argument provided is different from the number of argument provided to the method
it is obvious that the error is related to connectivity issue since I have tried the same Excel file on the on the server and successfully imported.
in order to prevent this issue I was thinking to alternative solution rather than looping the through the excel file and do the business and insert the records, instead I thought it might be useful if I save the file directly/ bulk save in a table or something else then try to loop through the table to prevent the connectivity issue.
note: several solution are available on google such as windows ghosting but none works for me
could anyone please advise about that or suggest the suitable solution
I would recommend you save the Excel file as tab-separated text, then do the import using the TextIO class.
You will also benefit from a +10 times increase in performance!
static void ExcelTest(Args _args)
{
#Excel
FilePath excelFile = #'C:\Users\user\Documents\MyExcelFile.xlsx';
FilePath textFile = #'C:\Users\user\Documents\MyTextFile.txt';
Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbooks workBooks = application.get_Workbooks();
Microsoft.Office.Interop.Excel.Workbook workBook;
// Save the excel file as tab-separated text
application.set_DisplayAlerts(false);
application.set_Visible(false);
new FileIOPermission(excelFile, 'r').assert();
workBooks.Open(excelFile, 0, true, 5, '', '', true, #xlWindows, '', false, false, 1, false, false, 1);
CodeAccessPermission::revertAssert();
workBook = workBooks.get_Item(1);
new FileIOPermission(textFile, 'w').assert();
CodeAccessPermission::revertAssert();
workBook.SaveAs(textFile, #xlTextWindows, '', '', false, false, null, #xlLocalSessionChanges, false, null, null, false);
workBooks.Close();
application.Quit();
// Now read the text file
new FileIOPermission(textFile, 'r').assert();
io = new TextIo(textFile, 'r');
if (!io)
throw error("#SYS18447");
io.inFieldDelimiter('\t');
for (con = io.read(); io.status() == IO_Status::Ok; con = io.read())
{
info(con2str(con));
}
}
//load the excel library
$this->load->library('excel');
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file);
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only. of course this can be modified to suit your need.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
This is my reader code. I'm not able to read the date in my Excel file using this code; it's returning the code like 030567 some thing.
My Excel file has the date value but this code is not returning the date. I don't know how to resolve this issue.
You need to use format like below code:
getCellByColumnAndRow($col, $row)->getValue())->format('m/d/Y');
Hope this will resolve your problem.
Or you can also try this:
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
$phpDateTimeObject = PHPExcel_Shared_Date::ExcelToPHPObject($data_value);
echo phpDateTimeObject->format('Y-m-d');
I want to delete all rows that start with "//", from Excel sheet, with PHPExcel.
My code:
require '../Classes/PHPExcel.php';
require_once '../Classes/PHPExcel/IOFactory.php';
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE);
$path = "del_head.xls";
$objPHPExcel = PHPExcel_IOFactory::load($path);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for($row=1; $row < $highestRow; ++$row){
$value = $objPHPExcel->getActiveSheet()->getCell('A'.$row)->getValue();
if (substr($value,0,2) == "//") {
$objPHPExcel->getActiveSheet()->removeRow($row, $row);
}
}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, "Excel2007");
$objWriter->save($path);
But, the code not delete all rows that start with "//".
I think the problem is with function 'removeRow'.
Thank you very much in advance.
Replace this line
$objPHPExcel->getActiveSheet()->removeRow($row, $row);
with
$objPHPExcel->getActiveSheet()->removeRow($row);
There's one obvious problem with your call to removeRow(): The first argument is the starting row, the second is the number of rows to remove; so if you find a // at row 5, then you're telling PHPExcel to remove 5 rows starting from row 5 (i.e. rows 5 to 9).
You're also reading a file with a .xls extension (assuming that it's a BIFF file from the extension), but saving with the same .xls filename as an OfficeOpenXML file (which is normally a .xlsx file).
So what format actually is your file? What does a call to the IOFactory's identify() method recognise it as? If it's actually a comma- or tab-separated value file (most likely to have a leading //), then you'd be better using PHP's fgetcsv() and fputcsv() functions to process it to remove those lines.
Try this code, Its worked me
$filename = 'path/example.xls';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($filename);
$objWorksheet = $objPHPExcel->getActiveSheet();
$row_id = 1; // deleted row id
$number_rows = 2; // number of rows count
if ($objWorksheet != NULL) {
if ($objWorksheet->removeRow($row_id, $number_rows)) {
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save($filename);
}
}
Please, check the value assigned on line:
$highestRow = $objWorksheet->getHighestRow();
I've tested this code and the value is always 1
I'm having the following code that I'm using to load, read, write and download an excel file.
//include PHPExcel library
require_once "Classes/PHPExcel/IOFactory.php";
//load Excel template file
$objTpl = PHPExcel_IOFactory::load("excel.xls");
$objTpl->setActiveSheetIndex(0); //set first sheet as active
$objTpl->getActiveSheet()->setCellValue('C2', date('Y-m-d')); //set C1 to current date
$objTpl->getActiveSheet()->getStyle('C2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); //C1 is right-justified
$strData = $objTpl->getActiveSheet()->getCell('C3')->getValue();
$strData .= $objTpl->getActiveSheet()->getCell('C4')->getValue();
$objTpl->getActiveSheet()->setCellValue('C3', 'It\'s working');
$objTpl->getActiveSheet()->setCellValue('C4', 'Dynamic excel read and writing');
$objTpl->getActiveSheet()->setCellValue('C6', 'Data read: C3 = '.substr($strData,0,1).' and C4 = '.substr($strData,1,1));
$objTpl->getActiveSheet()->getStyle('C4')->getAlignment()->setWrapText(true); //set wrapped for some long text message
$objTpl->getActiveSheet()->getColumnDimension('C')->setWidth(40); //set column C width
$objTpl->getActiveSheet()->getRowDimension('4')->setRowHeight(120); //set row 4 height
$objTpl->getActiveSheet()->getStyle('A4:C4')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP); //A4 until C4 is vertically top-aligned
//prepare download
$filename=mt_rand(1,100000).'.xls'; //just some random filename
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objTpl, 'Excel5'); //downloadable file is in Excel 2003 format (.xls)
$objWriter->save('php://output'); //send it to user, of course you can save it to disk also!
My problem is that I want to load the excel file from a different source(url,stream), not from the local directory
Simply save the file to your server and then read it.
file_put_contents('excel.xls',
file_get_contents('https://www.myweburl.com/spreadsheets.xls')
);
$objTpl = PHPExcel_IOFactory::load("excel.xls");