简体   繁体   中英

How to fit <td> width to content when exporting to XLS cell

I have a code that converts HTML tables to XLS format like this:

$fileNameXls = 'report.xls'; 
$result = "
<table>
  <tr>
    <th>Brand</th>
    <th>Heroes</th>
  </tr>
  <tr>
    <td> Marvel </td>
    <td> Spiderman, Batman, Power Ranger, Power Puffgirl, and booya </td>
  </tr>
</table>
";


$result = $header.$body;
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$fileNameXls");
echo $result;

The problem is, when I open the XLS file the cell that contains the row in the HTML table seems to have a fixed width, and the width is not following the row content width, so it becomes overlapped like this:

例

The real problem is that you are not saving an XLS file, it remains an HTML but with XLS extension. MS Excel only displays the html file and probably you are also getting an warning that the file format is invalid when you open the file.

For a real Excel file, you should use an Excel library like PHPExcel or EasyXLS and the column width can de automatically adjusted to fit cell content. I also recommend you to use the latest XLSX Excel file format, instead of the old XLS file format.

The best you can try with your code is to set an approximated column width for tags.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM