CsvExcelCompatibilityTest.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheetTests\Writer\Csv;
  3. use PhpOffice\PhpSpreadsheet\Reader\Csv as CsvReader;
  4. use PhpOffice\PhpSpreadsheet\Shared\File;
  5. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  6. use PhpOffice\PhpSpreadsheet\Writer\Csv as CsvWriter;
  7. use PhpOffice\PhpSpreadsheetTests\Functional;
  8. class CsvExcelCompatibilityTest extends Functional\AbstractFunctional
  9. {
  10. // Excel seems to have changed with how they handle this.
  11. // In particular, it does not recognize UTF-8 non-ASCII characters
  12. // if a file is written with ExcelCompatibility on.
  13. // The initial 'sep=;' line seems to confuse it, even though
  14. // it has a BOM. The Unix "file" command also indicates a difference
  15. // when the sep line is or is not included:
  16. // UTF-8 Unicode (with BOM) text, with CRLF line terminators
  17. // vs CSV text (without sep line, with or without BOM)
  18. // So, this test has no UTF-8 yet while more research is conducted.
  19. public function testExcelCompatibility(): void
  20. {
  21. $spreadsheet = new Spreadsheet();
  22. $sheet = $spreadsheet->getActiveSheet();
  23. $sheet->setCellValue('A1', '1');
  24. $sheet->setCellValue('B1', '2');
  25. $sheet->setCellValue('C1', '3');
  26. $sheet->setCellValue('A2', '4');
  27. $sheet->setCellValue('B2', '5');
  28. $sheet->setCellValue('C2', '6');
  29. $writer = new CsvWriter($spreadsheet);
  30. $writer->setExcelCompatibility(true);
  31. self::assertSame('', $writer->getOutputEncoding());
  32. $filename = File::temporaryFilename();
  33. $writer->save($filename);
  34. $reader = new CsvReader();
  35. $spreadsheet2 = $reader->load($filename);
  36. $contents = file_get_contents($filename);
  37. unlink($filename);
  38. self::assertEquals(1, $spreadsheet2->getActiveSheet()->getCell('A1')->getValue());
  39. self::assertEquals(6, $spreadsheet2->getActiveSheet()->getCell('C2')->getValue());
  40. self::assertStringContainsString(CsvReader::UTF8_BOM, $contents);
  41. self::assertStringContainsString("\r\n", $contents);
  42. self::assertStringContainsString('sep=;', $contents);
  43. self::assertStringContainsString('"1";"2";"3"', $contents);
  44. self::assertStringContainsString('"4";"5";"6"', $contents);
  45. }
  46. }