From 5faaccd8275535483cb18705b25720b21ba7cb67 Mon Sep 17 00:00:00 2001
From: Dalpil <47555+dalpil@users.noreply.github.com>
Date: Tue, 12 Dec 2023 18:11:07 +0100
Subject: [PATCH] Bugfix: Use UTF-16LE for encoding XLS sheet names

This is a backport of the original work by cfhay on Spreadsheet_Excel_Writer
---
 functions/PEAR/Spreadsheet/Excel/Writer/Workbook.php | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/functions/PEAR/Spreadsheet/Excel/Writer/Workbook.php b/functions/PEAR/Spreadsheet/Excel/Writer/Workbook.php
index 4b3cbf50..6cd72019 100755
--- a/functions/PEAR/Spreadsheet/Excel/Writer/Workbook.php
+++ b/functions/PEAR/Spreadsheet/Excel/Writer/Workbook.php
@@ -326,6 +326,10 @@ class Spreadsheet_Excel_Writer_Workbook extends Spreadsheet_Excel_Writer_BIFFwri
             if (strlen($name) > 31) {
                 return $this->raiseError("Sheetname $name must be <= 31 chars");
             }
+        } else {
+            if (function_exists('iconv')) {
+                $name = iconv('UTF-8', 'UTF-16LE', $name);
+            }
         }
 
         // Check that the worksheet name doesn't already exist: a fatal Excel error.
@@ -932,11 +936,15 @@ class Spreadsheet_Excel_Writer_Workbook extends Spreadsheet_Excel_Writer_BIFFwri
         }
 
         $grbit     = 0x0000;                    // Visibility and sheet type
-        $cch       = strlen($sheetname);        // Length of sheet name
+        if ($this->_BIFF_version == 0x0600) {
+            $cch = mb_strlen($sheetname, 'UTF-16LE'); // Length of sheet name
+        } else {
+            $cch = strlen($sheetname); // Length of sheet name
+        }
 
         $header    = pack("vv",  $record, $length);
         if ($this->_BIFF_version == 0x0600) {
-            $data      = pack("Vvv", $offset, $grbit, $cch);
+            $data      = pack("VvCC", $offset, $grbit, $cch, 0x1);
         } else {
             $data      = pack("VvC", $offset, $grbit, $cch);
         }
-- 
GitLab