PHPExcel icon indicating copy to clipboard operation
PHPExcel copied to clipboard

Removing empty columns and rows

Open sashabeep opened this issue 8 years ago • 3 comments

Hi, guys, can you please tell me how to load XLS file and save it as static html page without empty rows/columns

My current listing is

require_once 'assets/libs/phpexcel/PHPExcel/IOFactory.php';
$xls=$_GET['xls']; //example

if (!file_exists($xls)) {
	$out = "<p style=\"padding:1rem\">No table attached</p>";
    return $out;
}else{

//new file name
$htm=str_replace('.xlsx','.htm',$xls);
//read
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($xls);
//saving to html
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'HTML');
$objWriter->setSheetIndex(0);
$objWriter->save(str_replace('.xlsx', '.htm', $xls));
//read from file
$table=file_get_contents($htm);
$output=substr($table,strpos($table,'<body>'),strpos($table,'</body>')-strpos($table,'<body>'));
$output=str_replace('border="0" cellpadding="0" cellspacing="0"','border="1" cellpadding="1" cellspacing="1"',$output);
echo $output;
}

Result produces large amount of empty columns and rows(cut) 2017-02-06 16 32 46

how to avoid empty cells? Attached sample file 01.xlsx

sashabeep avatar Feb 06 '17 13:02 sashabeep

Here is a snippet from my code, which should only load the data that is actually written. Maybe it will be of help to you:

/**
 * Reads the data from the file
 *
 * @return  array  Excel data
 */
public function getData()
{
    $loader = \PHPExcel_IOFactory::createReaderForFile($this->filename);
    $loader->setReadDataOnly(true);

    // Load only the first sheet
    $worksheets = $loader->listWorkSheetNames($this->filename);
    $loader->setLoadSheetsOnly($worksheets[0]);

    $reader = $loader->load($this->filename);
    $sheet = $reader->getActiveSheet();

    $highestRow = $sheet->getHighestRow();
    $highestCol = $sheet->getHighestColumn();

    return $sheet->rangeToArray("A1:$highestCol$highestRow", null, true, false, false);
}

AmazingDreams avatar Mar 01 '17 09:03 AmazingDreams

/**
 * Reads the data from the file
 *
 * @return  array  Excel data
 */
public function getData()
{
    $loader = \PHPExcel_IOFactory::createReaderForFile($this->filename);
    $loader->setReadDataOnly(true);
    $reader = $loader->load($this->filename);
    $sheet = $reader->setActiveSheetIndex(0);
    return $sheet->toArray();
}

radiocity avatar Feb 13 '18 15:02 radiocity

$highestRow = $sheet->getHighestRow(); $highestCol = $sheet->getHighestColumn();

Dont ignore empty columns and rows. If you have 100 lines of data an 2000 empty rows, you will get 2100 as result.

0xCardiE avatar Oct 16 '18 12:10 0xCardiE