Related
I have a PHP script show below that queries for all rows. The result set only shows one row even though there are more.
mbrlist.php
`<?php
$html = "";
class MyDB extends SQLite3
{
function __construct()
{
$this->open('privdata/helpseekers.db');
}
}
$db = new MyDB();
if ( !$db )
{
echo $db->lastErrorMsg();
}
else
{
$rows = $db->query("SELECT COUNT(id) as count FROM accounts");
$row = $rows->fetchArray(SQLITE3_ASSOC);
$numRows = $row['count'];
echo "Opened database successfully - " . $numRows . " Accounts Found\n";
}
$ret = $db->query("SELECT id,userid,fname,lname,password,email,userrole FROM accounts ORDER BY id ASC");
while ( $rec = $ret->fetchArray() )
{
$html = " <td>{$rec[0]}</td> <td>{$rec[1]}</td> <td>{$rec[2]}</td> <td>{$rec[3]}</td> <td>{$rec[4]}</td> <td>{$rec[5]}</td> <td>{$rec[6]}</td> </tr>\n";
if ( !$rec = $ret->fetchArray() ) break;
}
$db->close();
echo $html;
?>`
So why does it not return more than one row?
In the loop you do :
// Before loop variable html contains ""
// on next line you set into $rec the next row data
// in case there is no more row you exit or not not enter the loop
while ( $rec = $ret->fetchArray() )
{
// anything that was inside $html before this assignment is replaced
// by <td>...</td> of current row
$html = " <td>{$rec[0]}</td> <td>{$rec[1]}</td> <td>{$rec[2]}</td> <td>{$rec[3]}</td> <td>{$rec[4]}</td> <td>{$rec[5]}</td> <td>{$rec[6]}</td> </tr>\n";
// here you get the next row in $rec and test if it is not null
// if it is null you exit the loop
if ( !$rec = $ret->fetchArray() ) break;
// at the end of the loop, the code in while ($rec = ...) is
// executed to get row of next data
}
$db->close();
// here you send the contents of $html to client browser
echo $html;
I'm having trouble in getting the correct characters from my .xls file.
Based on what I found on the internet, it seems that it has something to do with the encoding or its something about html that cant be read through PHPexcel. It says that for PHPExcel to read the file it has to be utf-8. Can you give me hints on how to get the correct encoding or getting to read it by utf-8?
Here's my code:
require_once 'Classes/PHPExcel.php';
include 'Classes/PHPExcel/IOFactory.php';
$pathgalleriadeclare = "C:\Users\Desktop\sample.xls";
try {
$inputfiletype = PHPExcel_IOFactory::identify($pathgalleriadeclare);
$objReader = PHPExcel_IOFactory::createReader($inputfiletype);
$objReader->setInputEncoding('ISO-8859-1');
utf8_encode($objReader);
$objPHPExcel = $objReader->load($pathgalleriadeclare);
} catch(Exception $e){
die('Error loading file "' .pathinfo($pathgalleriadeclare, PATHINFO_BASENAME).'": '.$e->getMessage());
}
$sheet = $objPHPExcel->getSheet(0);
$highRow = $sheet->getHighestRow();
$highColumn = $sheet->getHighestColumn();
for ($row = 7; $row <= $highRow; $row++){
//REPORT
$value = $objPHPExcel->getSheet(0)->getCell('A'.$row)->getValue();
echo $value ;
echo "<br />";
}
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
exit();
Here's a sample output:
So, I'm a fairly new PHP programmer and I'm trying to set up a page that uploads a file, displays the info in a table, then writes the data to a database.
I've got these things working (I found some helpful code online) however my dates are displaying incorrectly.
For example, the date "2/15/2017 17:55" is displaying as "42781.746527778".
Here is the code:
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME)
. '": ' . $e->getMessage());
}
echo '<center><table style="width:50%;" border=1>';
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for ($row = 1; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL, TRUE, FALSE);
echo "<tr>";
foreach($rowData[0] as $k=>$v)
echo "<td>".$v."</td>";
echo "</tr>";
}
echo '</table></center>';
}
else{
echo '<p style="color:red;">Please upload file with xlsx extension only.</p>';
}
I get why it is displaying the date that way, however I'm not having luck in fixing it when trying to display the entire column as a date and time, or displaying it in a single cell as the correct date and time.
var_dump($objPHPExcel->getActiveSheet()->getCell('B2')->getFormattedValue());
This code displays the correct date and time for one of my sample spreadsheets, however I'm not able to get that value in the cell.
Any help would be appreciated. Thank you!
I believe this is what you are looking for? Check if the cell is a Excel date and time then extract and convert the Excel date to a PHP date.
if(PHPExcel_Shared_Date::isDateTime($k)) {
$v = date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($v));
}
I am quite new to PHPExcel and learning PHP as I go. I managed to get PHPexcel to export my data from SQL via the code below. Right now its just outputting in basic style, meaning its just serialized the data from SQL and next record would show up in the next row. I added an image of what I would like to accomplish, is this something possible with PHPexcel or am I dreaming.
If anyone could send me a quick example of how to accomplish this it would be greatly appreciated.
Image
http://postimg.org/image/m3n60hn25/
Below is a working sample of a simple serialized export.
<?php
// connection with the database
$dbhost = "localhost";
$dbuser = "IMC_COE2";
$dbpass = "XXX";
$dbname = "IMC_COE2";
mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname);
// require the PHPExcel file
require '/Excelphp/Classes/PHPExcel.php';
// simple query
$query = 'SELECT client, team_name,support_team_prime,prime_comments,support_team_backup,backup_comments,escalation1,escalation1_comments,escalation2,escalation2_comments,escalation3,escalation3_comments,escalation4,escalation4_comments,note FROM tbl_address ORDER by team_name DESC';
$headings = array('Client Name','Team Name','Prime Contact','Comments','Backup Contacts','Comments','Escalation 1','Comments','Escalation 2','Comments','Escalation 3','Comments','Escalation 4','Comments','Additional notes');
if ($result = mysql_query($query) or die(mysql_error())) {
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('List of Users');
$rowNumber = 1;
$col = 'A';
foreach($headings as $heading) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
$col++;
}
// Loop through the result set
$rowNumber = 2;
while ($row = mysql_fetch_row($result)) {
$col = 'A';
foreach($row as $cell) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
$col++;
}
$rowNumber++;
}
// Freeze pane so that the heading line won't scroll
$objPHPExcel->getActiveSheet()->freezePane('A2');
// Save as an Excel BIFF (xls) file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="userList.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit();
}
echo 'a problem has occurred... no data retrieved from the database';
UPDATE October 2nd:
Here is where I am at now, the only problem I have is that PHPExcel's export is only showing 1 record. I cant figureout the missing code that will show me all the records in the same format and cell array.
Image:
http://postimg.org/image/8gicg5gtl/8a918f3e/
Heres my progress so far but still not getting a successful loop:
<?php
/** PHPExcel */
require_once '/Excelphp/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
$objPHPExcel->getActiveSheet()->mergeCells('B2:D2');
$objPHPExcel->getActiveSheet()->mergeCells('B4:D4');
$objPHPExcel->getActiveSheet()->mergeCells('B7:D7');
$objPHPExcel->getActiveSheet()->mergeCells('B12:D12');
$objPHPExcel->getActiveSheet()->mergeCells('C3:D3');
$objPHPExcel->getActiveSheet()->mergeCells('B13:D13');
$objPHPExcel->getActiveSheet()->getStyle('C3:D3')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C5:D5')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C6:D6')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C8:D8')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C9:D9')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C10:D10')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C11:D11')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('B13:D13')->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(false);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(50);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(50);
//Setting for borders
$styleArray = array('borders' => array('outline' => array('style' => PHPExcel_Style_Border::BORDER_THIN,'color' => array('argb' => 'FFA0A0A0'),),),);
$objPHPExcel->getActiveSheet()->getStyle('B2:B13')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('C2:C13')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('D2:D13')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B2:D2')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B3:D3')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B4:D4')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B5:D5')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B6:D6')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B7:D7')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B8:D8')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B9:D9')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B10:D10')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B11:D11')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B12:D12')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B13:D13')->applyFromArray($styleArray);
//Background color on cells
$objPHPExcel->getActiveSheet()->getStyle('B2:D2')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFCCE5FF');
$objPHPExcel->getActiveSheet()->getStyle('B4:D4')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFCCE5FF');
$objPHPExcel->getActiveSheet()->getStyle('B7:D7')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFCCE5FF');
$objPHPExcel->getActiveSheet()->getStyle('B12:D12')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFCCE5FF');
$objPHPExcel->getActiveSheet()->getStyle('B7:D7')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFCCE5FF');
$objPHPExcel->getActiveSheet()->getStyle('B3')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
$objPHPExcel->getActiveSheet()->getStyle('B5')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
$objPHPExcel->getActiveSheet()->getStyle('B6')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
$objPHPExcel->getActiveSheet()->getStyle('B8')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
$objPHPExcel->getActiveSheet()->getStyle('B9')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
$objPHPExcel->getActiveSheet()->getStyle('B10')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
$objPHPExcel->getActiveSheet()->getStyle('B11')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE0E0E0');
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', '')
->setCellValue('B1', '')
->setCellValue('C1', '')
->setCellValue('D1', '')
->setCellValue('E1', '')
->setCellValue('A14', '')
->setCellValue('B14', '')
->setCellValue('C14', '')
->setCellValue('D14', '')
->setCellValue('E14', '')
->setCellValue('B3', 'Client:')
->setCellValue('B5', 'Prime:')
->setCellValue('B4', 'Support group contacts')
->setCellValue('B6', 'Backup:')
->setCellValue('B7', 'Escalations')
->setCellValue('B8', 'Escalation 1:')
->setCellValue('B9', 'Escalation 2:')
->setCellValue('B10', 'Escalation 3:')
->setCellValue('B11', 'Escalation 4:')
->setCellValue('B12', 'Notes');
// SQl database connections
$db = mysql_connect("localhost", "IMC_COE2", "IMC123");
mysql_select_db("IMC_COE2",$db);
$sql="select client, team_name,support_team_prime,prime_comments,support_team_backup,backup_comments,escalation1,escalation1_comments,escalation2,escalation2_comments,escalation3,escalation3_comments,escalation4,escalation4_comments,note from tbl_address ORDER by team_name";
$result=mysql_query($sql);
$numrows=mysql_num_rows($result);
if ($numrows>0)
{
$row=2;
while($data=mysql_fetch_array($result))
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('C'.$row, $data['client'])
->setCellValue('B'.$row, $data['team_name'])
->setCellValue('C'.($row+3), $data['support_team_prime'])
->setCellValue('D'.($row+3), $data['prime_comments'])
->setCellValue('C'.($row+4), $data['support_team_backup'])
->setCellValue('D'.($row+4), $data['backup_comments'])
->setCellValue('C'.($row+6), $data['escalation1'])
->setCellValue('D'.($row+6), $data['escalation1_comments'])
->setCellValue('C'.($row+7), $data['escalation2'])
->setCellValue('D'.($row+7), $data['escalation2_comments'])
->setCellValue('C'.($row+8), $data['escalation3'])
->setCellValue('D'.($row+8), $data['escalation3_comments'])
->setCellValue('C'.($row+9), $data['escalation4'])
->setCellValue('D'.($row+9), $data['escalation4_comments'])
->setCellValue('B'.($row+10), $data['note']);
}
}
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle('Directory Tool Full dump');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel5)
ob_end_clean();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Export-Directory Tool.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit;
?>
Here is the final result, still needs tweaking but big thanks to Mark Baker who helped me out. It takes about 1-2 minutes to load the excel file but it works. I gonna figure out how to optimize the code for best performance.
<?php
/** PHPExcel */
require_once '/Excelphp/Classes/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
$rows=2;
//This is the hard coded *non dynamic* cell formatting
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(50);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(50);
$objPHPExcel->getActiveSheet()->getSheetView()->setZoomScale(85);
// SQl database connections
$db = mysql_connect("localhost", "IMC_COE2", "IMC123");
mysql_select_db("IMC_COE2",$db);
$sql="select client, team_name,support_team_prime,prime_comments,support_team_backup,backup_comments,escalation1,escalation1_comments,escalation2,escalation2_comments,escalation3,escalation3_comments,escalation4,escalation4_comments,note from tbl_address ORDER by team_name";
$result=mysql_query($sql);
$numrows=mysql_num_rows($result);
if ($numrows>0)
{
while($data=mysql_fetch_array($result))
{
//This section is the actual data import fromt he SQL database *dont touch*
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('C'.($rows+1), $data['client']) //this will give cell C2.
->setCellValue('B'.$rows, $data['team_name']) // this will give cell B2
->setCellValue('C'.($rows+3), $data['support_team_prime']) //this will give C5
->setCellValue('D'.($rows+3), $data['prime_comments']) // This will give D5
->setCellValue('C'.($rows+4), $data['support_team_backup']) //This will give C6
->setCellValue('D'.($rows+4), $data['backup_comments']) //This will give D6 etc...
->setCellValue('C'.($rows+6), $data['escalation1'])
->setCellValue('D'.($rows+6), $data['escalation1_comments'])
->setCellValue('C'.($rows+7), $data['escalation2'])
->setCellValue('D'.($rows+7), $data['escalation2_comments'])
->setCellValue('C'.($rows+8), $data['escalation3'])
->setCellValue('D'.($rows+8), $data['escalation3_comments'])
->setCellValue('C'.($rows+9), $data['escalation4'])
->setCellValue('D'.($rows+9), $data['escalation4_comments'])
->setCellValue('B'.($rows+11), $data['note']);
//Row height adjustments
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+3)
->setRowHeight(100);
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+4)
->setRowHeight(100);
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+6)
->setRowHeight(100);
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+7)
->setRowHeight(100);
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+8)
->setRowHeight(100);
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+9)
->setRowHeight(100);
$objPHPExcel->getActiveSheet()
->getRowDimension($rows+11)
->setRowHeight(100);
//Cell Merging
$objPHPExcel->getActiveSheet()->mergeCells('B'.$rows.':D'.$rows);
$objPHPExcel->getActiveSheet()->mergeCells('B'.($rows+2).':D'.($rows+2));
$objPHPExcel->getActiveSheet()->mergeCells('B'.($rows+5).':D'.($rows+5));
$objPHPExcel->getActiveSheet()->mergeCells('B'.($rows+10).':D'.($rows+10));
$objPHPExcel->getActiveSheet()->mergeCells('C'.($rows+1).':D'.($rows+1));
$objPHPExcel->getActiveSheet()->mergeCells('B'.($rows+11).':D'.($rows+11));
//Cell Wraptext
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+1).':D'.($rows+1))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+3).':D'.($rows+3))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+4).':D'.($rows+4))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+6).':D'.($rows+6))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+7).':D'.($rows+7))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+8).':D'.($rows+8))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('C'.($rows+9).':D'.($rows+9))->getAlignment()->setWrapText(true);
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+11).':D'.($rows+11))->getAlignment()->setWrapText(true);
//Background color on cells
$objPHPExcel->getActiveSheet()->getStyle('B'.$rows.':D'.$rows)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+2).':D'.($rows+2))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+5).':D'.($rows+5))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+10).':D'.($rows+10))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+1))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+3))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+4))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+6))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+7))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+8))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$objPHPExcel->getActiveSheet()->getStyle('B'.($rows+9))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('B'.($rows+1), 'Client:')
->setCellValue('B'.($rows+3), 'Prime:')
->setCellValue('B'.($rows+2), 'Support group contacts')
->setCellValue('B'.($rows+4), 'Backup:')
->setCellValue('B'.($rows+5), 'Escalations')
->setCellValue('B'.($rows+8), 'Escalation 1:')
->setCellValue('B'.($rows+7), 'Escalation 2:')
->setCellValue('B'.($rows+8), 'Escalation 3:')
->setCellValue('B'.($rows+9), 'Escalation 4:')
->setCellValue('B'.($rows+10), 'Notes');
$rows+=14;
}
}
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle('Directory Tool Full dump');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel5)
ob_end_clean();
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Export-Directory Tool.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit;
?>
Before reading anything else, please take time to read the original thread.
Overview: a .xfdl file is a gzipped .xml file which has then been encoded in base64. I wish to de-encode the .xfdl into xml which I can then modify and then re-encode back into a .xfdl file.
xfdl > xml.gz > xml > xml.gz > xfdl
I have been able to take a .xfdl file and de-encode it from base64 using uudeview:
uudeview -i yourform.xfdl
Then decommpressed it using gunzip
gunzip -S "" < UNKNOWN.001 > yourform-unpacked.xml
The xml produced is 100% readable and looks wonderful. Without modifying the xml then, i should be able to re-compress it using gzip:
gzip yourform-unpacked.xml
Then re-encoded in base-64:
base64 -e yourform-unpacked.xml.gz yourform_reencoded.xfdl
If my thinking is correct, the original file and the re-encoded file should be equal. If I put yourform.xfdl and yourform_reencoded.xfdl into beyond compare, however, they do not match up. Also, the original file can be viewed in an http://www.grants.gov/help/download_software.jsp#pureedge">.xfdl viewer. The viewer says that the re-encoded xfdl is unreadable.
I have also tried uuenview to re-encode in base64, it also produces the same results. Any help would be appreciated.
As far as I know you cannot find the compression level of an already compressed file. When you are compressing the file you can specify the compression level with -# where the # is from 1 to 9 (1 being the fastest compression and 9 being the most compressed file). In practice you should never compare a compressed file with one that has been extracted and recompressed, slight variations can easily crop up. In your case I would compare the base64 encoded versions instead of the gzip'd versions.
Check these out:
http://www.ourada.org/blog/archives/375
http://www.ourada.org/blog/archives/390
They are in Python, not Ruby, but that should get you pretty close.
And the algorithm is actually for files with header 'application/x-xfdl;content-encoding="asc-gzip"' rather than 'application/vnd.xfdl; content-encoding="base64-gzip"'
But the good news is that PureEdge (aka IBM Lotus Forms) will open that format with no problem.
Then to top it off, here's a base64-gzip decode (in Python) so you can make the full round-trip:
with open(filename, 'r') as f:
header = f.readline()
if header == 'application/vnd.xfdl; content-encoding="base64-gzip"\n':
decoded = b''
for line in f:
decoded += base64.b64decode(line.encode("ISO-8859-1"))
xml = zlib.decompress(decoded, zlib.MAX_WBITS + 16)
I did this in Java with the help of the Base64 class from http://iharder.net/base64.
I've been working on an application to do form manipulation in Java. I decode the file, create an DOM document from the XML then write it back to file.
My code in Java to read the file looks like this:
public XFDLDocument(String inputFile)
throws IOException,
ParserConfigurationException,
SAXException
{
fileLocation = inputFile;
try{
//create file object
File f = new File(inputFile);
if(!f.exists()) {
throw new IOException("Specified File could not be found!");
}
//open file stream from file
FileInputStream fis = new FileInputStream(inputFile);
//Skip past the MIME header
fis.skip(FILE_HEADER_BLOCK.length());
//Decompress from base 64
Base64.InputStream bis = new Base64.InputStream(fis,
Base64.DECODE);
//UnZIP the resulting stream
GZIPInputStream gis = new GZIPInputStream(bis);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(gis);
gis.close();
bis.close();
fis.close();
}
catch (ParserConfigurationException pce) {
throw new ParserConfigurationException("Error parsing XFDL from file.");
}
catch (SAXException saxe) {
throw new SAXException("Error parsing XFDL into XML Document.");
}
}
My code in java looks like this to write the file to disk:
/**
* Saves the current document to the specified location
* #param destination Desired destination for the file.
* #param asXML True if output needs should be as un-encoded XML not Base64/GZIP
* #throws IOException File cannot be created at specified location
* #throws TransformerConfigurationExample
* #throws TransformerException
*/
public void saveFile(String destination, boolean asXML)
throws IOException,
TransformerConfigurationException,
TransformerException
{
BufferedWriter bf = new BufferedWriter(new FileWriter(destination));
bf.write(FILE_HEADER_BLOCK);
bf.newLine();
bf.flush();
bf.close();
OutputStream outStream;
if(!asXML) {
outStream = new GZIPOutputStream(
new Base64.OutputStream(
new FileOutputStream(destination, true)));
} else {
outStream = new FileOutputStream(destination, true);
}
Transformer t = TransformerFactory.newInstance().newTransformer();
t.transform(new DOMSource(doc), new StreamResult(outStream));
outStream.flush();
outStream.close();
}
Hope that helps.
I've been working on something like that and this should work for php. You must have a writable tmp folder and the php file be named example.php!
<?php
function gzdecode($data) {
$len = strlen($data);
if ($len < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {
echo "FILE NOT GZIP FORMAT";
return null; // Not GZIP format (See RFC 1952)
}
$method = ord(substr($data,2,1)); // Compression method
$flags = ord(substr($data,3,1)); // Flags
if ($flags & 31 != $flags) {
// Reserved bits are set -- NOT ALLOWED by RFC 1952
echo "RESERVED BITS ARE SET. VERY BAD";
return null;
}
// NOTE: $mtime may be negative (PHP integer limitations)
$mtime = unpack("V", substr($data,4,4));
$mtime = $mtime[1];
$xfl = substr($data,8,1);
$os = substr($data,8,1);
$headerlen = 10;
$extralen = 0;
$extra = "";
if ($flags & 4) {
// 2-byte length prefixed EXTRA data in header
if ($len - $headerlen - 2 < 8) {
return false; // Invalid format
echo "INVALID FORMAT";
}
$extralen = unpack("v",substr($data,8,2));
$extralen = $extralen[1];
if ($len - $headerlen - 2 - $extralen < 8) {
return false; // Invalid format
echo "INVALID FORMAT";
}
$extra = substr($data,10,$extralen);
$headerlen += 2 + $extralen;
}
$filenamelen = 0;
$filename = "";
if ($flags & 8) {
// C-style string file NAME data in header
if ($len - $headerlen - 1 < 8) {
return false; // Invalid format
echo "INVALID FORMAT";
}
$filenamelen = strpos(substr($data,8+$extralen),chr(0));
if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {
return false; // Invalid format
echo "INVALID FORMAT";
}
$filename = substr($data,$headerlen,$filenamelen);
$headerlen += $filenamelen + 1;
}
$commentlen = 0;
$comment = "";
if ($flags & 16) {
// C-style string COMMENT data in header
if ($len - $headerlen - 1 < 8) {
return false; // Invalid format
echo "INVALID FORMAT";
}
$commentlen = strpos(substr($data,8+$extralen+$filenamelen),chr(0));
if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {
return false; // Invalid header format
echo "INVALID FORMAT";
}
$comment = substr($data,$headerlen,$commentlen);
$headerlen += $commentlen + 1;
}
$headercrc = "";
if ($flags & 1) {
// 2-bytes (lowest order) of CRC32 on header present
if ($len - $headerlen - 2 < 8) {
return false; // Invalid format
echo "INVALID FORMAT";
}
$calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;
$headercrc = unpack("v", substr($data,$headerlen,2));
$headercrc = $headercrc[1];
if ($headercrc != $calccrc) {
echo "BAD CRC";
return false; // Bad header CRC
}
$headerlen += 2;
}
// GZIP FOOTER - These be negative due to PHP's limitations
$datacrc = unpack("V",substr($data,-8,4));
$datacrc = $datacrc[1];
$isize = unpack("V",substr($data,-4));
$isize = $isize[1];
// Perform the decompression:
$bodylen = $len-$headerlen-8;
if ($bodylen < 1) {
// This should never happen - IMPLEMENTATION BUG!
echo "BIG OOPS";
return null;
}
$body = substr($data,$headerlen,$bodylen);
$data = "";
if ($bodylen > 0) {
switch ($method) {
case 8:
// Currently the only supported compression method:
$data = gzinflate($body);
break;
default:
// Unknown compression method
echo "UNKNOWN COMPRESSION METHOD";
return false;
}
} else {
// I'm not sure if zero-byte body content is allowed.
// Allow it for now... Do nothing...
echo "ITS EMPTY";
}
// Verifiy decompressed size and CRC32:
// NOTE: This may fail with large data sizes depending on how
// PHP's integer limitations affect strlen() since $isize
// may be negative for large sizes.
if ($isize != strlen($data) || crc32($data) != $datacrc) {
// Bad format! Length or CRC doesn't match!
echo "LENGTH OR CRC DO NOT MATCH";
return false;
}
return $data;
}
echo "<html><head></head><body>";
if (empty($_REQUEST['upload'])) {
echo <<<_END
<form enctype="multipart/form-data" action="example.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<table>
<th>
<input name="uploadedfile" type="file" />
</th>
<tr>
<td><input type="submit" name="upload" value="Convert File" /></td>
</tr>
</table>
</form>
_END;
}
if (!empty($_REQUEST['upload'])) {
$file = "tmp/" . $_FILES['uploadedfile']['name'];
$orgfile = $_FILES['uploadedfile']['name'];
$name = str_replace(".xfdl", "", $orgfile);
$convertedfile = "tmp/" . $name . ".xml";
$compressedfile = "tmp/" . $name . ".gz";
$finalfile = "tmp/" . $name . "new.xfdl";
$target_path = "tmp/";
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
} else {
echo "There was an error uploading the file, please try again!";
}
$firstline = "application/vnd.xfdl; content-encoding=\"base64-gzip\"\n";
$data = file($file);
$data = array_slice($data, 1);
$raw = implode($data);
$decoded = base64_decode($raw);
$decompressed = gzdecode($decoded);
$compressed = gzencode($decompressed);
$encoded = base64_encode($compressed);
$decoded2 = base64_decode($encoded);
$decompressed2 = gzdecode($decoded2);
$header = bin2hex(substr($decoded, 0, 10));
$tail = bin2hex(substr($decoded, -8));
$header2 = bin2hex(substr($compressed, 0, 10));
$tail2 = bin2hex(substr($compressed, -8));
$header3 = bin2hex(substr($decoded2, 0, 10));
$tail3 = bin2hex(substr($decoded2, -8));
$filehandle = fopen($compressedfile, 'w');
fwrite($filehandle, $decoded);
fclose($filehandle);
$filehandle = fopen($convertedfile, 'w');
fwrite($filehandle, $decompressed);
fclose($filehandle);
$filehandle = fopen($finalfile, 'w');
fwrite($filehandle, $firstline);
fwrite($filehandle, $encoded);
fclose($filehandle);
echo "<center>";
echo "<table style='text-align:center' >";
echo "<tr><th>Stage 1</th>";
echo "<th>Stage 2</th>";
echo "<th>Stage 3</th></tr>";
echo "<tr><td>RAW DATA -></td><td>DECODED DATA -></td><td>UNCOMPRESSED DATA -></td></tr>";
echo "<tr><td>LENGTH: ".strlen($raw)."</td>";
echo "<td>LENGTH: ".strlen($decoded)."</td>";
echo "<td>LENGTH: ".strlen($decompressed)."</td></tr>";
echo "<tr><td><a href='tmp/".$orgfile."'/>ORIGINAL</a></td><td>GZIP HEADER:".$header."</td><td><a href='".$convertedfile."'/>XML CONVERTED</a></td></tr>";
echo "<tr><td></td><td>GZIP TAIL:".$tail."</td><td></td></tr>";
echo "<tr><td><textarea cols='30' rows='20'>" . $raw . "</textarea></td>";
echo "<td><textarea cols='30' rows='20'>" . $decoded . "</textarea></td>";
echo "<td><textarea cols='30' rows='20'>" . $decompressed . "</textarea></td></tr>";
echo "<tr><th>Stage 6</th>";
echo "<th>Stage 5</th>";
echo "<th>Stage 4</th></tr>";
echo "<tr><td>ENCODED DATA <-</td><td>COMPRESSED DATA <-</td><td>UNCOMPRESSED DATA <-</td></tr>";
echo "<tr><td>LENGTH: ".strlen($encoded)."</td>";
echo "<td>LENGTH: ".strlen($compressed)."</td>";
echo "<td>LENGTH: ".strlen($decompressed)."</td></tr>";
echo "<tr><td></td><td>GZIP HEADER:".$header2."</td><td></td></tr>";
echo "<tr><td></td><td>GZIP TAIL:".$tail2."</td><td></td></tr>";
echo "<tr><td><a href='".$finalfile."'/>FINAL FILE</a></td><td><a href='".$compressedfile."'/>RE-COMPRESSED FILE</a></td><td></td></tr>";
echo "<tr><td><textarea cols='30' rows='20'>" . $encoded . "</textarea></td>";
echo "<td><textarea cols='30' rows='20'>" . $compressed . "</textarea></td>";
echo "<td><textarea cols='30' rows='20'>" . $decompressed . "</textarea></td></tr>";
echo "</table>";
echo "</center>";
}
echo "</body></html>";
?>
You'll need to put the following line at the beginning of the XFDL file:
application/vnd.xfdl; content-encoding="base64-gzip"
After you've generated the base64-encoded file, open it in a text editor and paste the line above on the first line. Ensure that the base64'ed block starts at the beginning of the second line.
Save it and try it in the Viewer! If it still does not work, it may be that the changes that were made to the XML made it non-compliant in some manner. In this case, after the XML has been modified, but before it has been gzipped and base64 encoded, save it with an .xfdl file extension and try opening it with the Viewer tool. The viewer should be able to parse and display the uncompressed / unencoded file if it is in a valid XFDL format.
Different implementations of the gzip algorithm will always produce slightly different but still correct files, also the compression level of the original file may be different then what you are running it at.
gzip will put the filename in the header of file, so that a gzipped file vary in length depending on the filename of the uncompressed file.
If gzip acts on a stream, the filename is omitted and the file is a bit shorter, so the following should work:
gzip yourform-unpacked.xml.gz
Then re-encoded in base-64:
base64 -e yourform-unpacked.xml.gz yourform_reencoded.xfdl
maybe this will produce a file of the same length
Interesting, I'll give it a shot. The variations aren't slight, however. The newly encoded file is longer and when comparing the binary of the before and after, the data hardly matches up at all.
Before (the first three lines)
H4sIAAAAAAAAC+19eZOiyNb3/34K3r4RT/WEU40ssvTtrhuIuKK44Bo3YoJdFAFZ3D79C6hVVhUq
dsnUVN/qmIkSOLlwlt/JPCfJ/PGf9dwAlorj6pb58wv0LfcFUEzJknVT+/ml2uXuCSJP3kNf/vOQ
+TEsFVkgoDfdn18mnmd/B8HVavWt5TsKI2vKN8magyENiH3Lf9kRfpd817PmF+jpiOhQRFZcXTMV
After (the first three lines):
H4sICJ/YnEgAAzEyNDQ2LTExNjk2NzUueGZkbC54bWwA7D1pU+JK19/9FV2+H5wpByEhJMRH
uRUgCMom4DBYt2oqkAZyDQlmQZ1f/3YSNqGzKT3oDH6RdE4vOXuf08vFP88TFcygYSq6dnlM
naWOAdQGuqxoo8vjSruRyGYzfII6/id3dPGjVKwCBK+Zl8djy5qeJ5NPT09nTduAojyCZwN9
As you can see H4SI match up, then after that it's pandemonium.