Link to home
Create AccountLog in
Avatar of iceman19330
iceman19330

asked on

php writing to excel file row limit

I was wondering if there is a way to break up a csv file so that when it gets to 65000 rows it will start to create a 2nd csv file.  the editing needs to be done in excel and the less I have to ask them to manually do on their own the less hassel I get.
$out = '';
$fields = mysql_list_fields('','',$db);
$columns = mysql_num_fields($fields);
 
// Put the name of all fields
for ($i = 0; $i < $columns; $i++) {
$l=mysql_field_name($fields, $i);
$out .= '"'.$l.'",';
}
$out .="\n";
 
// Add all values in the table
while ($l = mysql_fetch_array($rsSearchResults)) {
for ($i = 0; $i < $columns; $i++) {
$out .='"'.$l["$i"].'",';
}
$out .="\n";
}
// Output to browser with appropriate mime type, you choose ;)
//header("Content-type: text/x-csv");
header("Content-type: text/csv");
//header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=search_results.csv");
echo $out;
exit;

Open in new window

Avatar of Sandeep Kothari
Sandeep Kothari
Flag of India image

try modifying the php code as follows.. might work...
// Put the name of all fields
for ($i = 0; $i < $columns; $i++) {
$l=mysql_field_name($fields, $i);
$hlist .= '"'.$l.'",';
}
$hlist .="\n";
 

// Add all values in the table
$m = 1;
$out = $hlist;
while ($l = mysql_fetch_array($rsSearchResults)) {
  for ($i = 0; $i < $columns; $i++) {
    $out .='"'.$l["$i"].'",';
  }
  $out .="\n";
  $m++;
  if($l > 65000){
     header("Content-type: text/csv");	
     header("Content-Disposition: attachment; filename=search_results.csv");
     echo $out;
     $out = $hlist;
  }
}

Open in new window

exit;
missed resetting $m ...

also reset $m in the condition of 65000 ...
try this.
try modifying the php code as follows:
// Put the name of all fields
for ($i = 0; $i < $columns; $i++) {
$l=mysql_field_name($fields, $i);
$hlist .= '"'.$l.'",';
}
$hlist .="\n";
 

// Add all values in the table
$m = 1;
$out = $hlist;
while ($l = mysql_fetch_array($rsSearchResults)) {
  for ($i = 0; $i < $columns; $i++) {
    $out .='"'.$l["$i"].'",';
  }
  $out .="\n";
  $m++;
  if($l > 65000){
     header("Content-type: text/csv");	
     header("Content-Disposition: attachment; filename=search_results.csv");
     echo $out;
     $m = 1;
     $out = $hlist;
  }
}
exit;

Open in new window

Avatar of iceman19330
iceman19330

ASKER

the 2nd file was looping out of control so not sure what happened there.
ASKER CERTIFIED SOLUTION
Avatar of Sandeep Kothari
Sandeep Kothari
Flag of India image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account