Skip to content

Excel 95 Cyrillic encoding problem #1018

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
boltunoreh opened this issue Jun 18, 2019 · 12 comments
Closed

Excel 95 Cyrillic encoding problem #1018

boltunoreh opened this issue Jun 18, 2019 · 12 comments

Comments

@boltunoreh
Copy link
Contributor

This is:

- [x] a bug report
- [ ] a feature request
- [ ] **not** a usage question (ask them on https://stackoverflow.com/questions/tagged/phpspreadsheet or https://gitter.im/PHPOffice/PhpSpreadsheet)

What is the expected behavior?

Excel 95 files with cyrillic text are processed fine

What is the current behavior?

Cyrillic text can't be decoded well because if excel file doesn't contain codepage record, CP1252 charset is used by default and it can't be changed explicitly

What are the steps to reproduce?

Step 1: find an excel 95 file with cyrillic text

Step 2:

<?php

require __DIR__ . '/vendor/autoload.php';

$inputFileName = './excel95.xls';

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
$spreadsheet = $reader->load($inputFileName);
$worksheet = $spreadsheet->getActiveSheet();

foreach ($worksheet->getRowIterator() as $row) {
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(FALSE);
    foreach ($cellIterator as $cell) {
        echo $cell->getValue() . PHP_EOL;
    }
}

Step 3: you can see that output contains bad symbols instead of valid cyrillic:

Êîñòþì ôëèñîâûé

Using iconv() or mb_convert_encoding() do not help while changing default codepage to CP1251 does. But there is no way to set codepage.

Which versions of PhpSpreadsheet and PHP are affected?

PhpSpreadsheet v. 1.7.0
PHP 5.6

@stale
Copy link

stale bot commented Aug 17, 2019

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.
If this is still an issue for you, please try to help by debugging it further and sharing your results.
Thank you for your contributions.

@stale stale bot added the stale label Aug 17, 2019
@stale stale bot closed this as completed Aug 24, 2019
@DmitrySkibitsky
Copy link

The problem is relevant at the moment.

@boltunoreh
Copy link
Contributor Author

The problem is relevant at the moment.

I've made a pull request to fix the issue #1484, but as far as I've never made pull requests to any 3rd party libs before, I'm not sure if it is correct or not. Also unfortunately I don't have enough time to add unit tests for this feature now, so I don't know is it acceptable or not.

Anyway you can use my fork until it is merged

@DmitrySkibitsky
Copy link

The problem is relevant at the moment.

I've made a pull request to fix the issue #1484, but as far as I've never made pull requests to any 3rd party libs before, I'm not sure if it is correct or not. Also unfortunately I don't have enough time to add unit tests for this feature now, so I don't know is it acceptable or not.

Anyway you can use my fork until it is merged

Thanks you.

@DmitrySkibitsky
Copy link

The problem is relevant at the moment.

I've made a pull request to fix the issue #1484, but as far as I've never made pull requests to any 3rd party libs before, I'm not sure if it is correct or not. Also unfortunately I don't have enough time to add unit tests for this feature now, so I don't know is it acceptable or not.

Anyway you can use my fork until it is merged

clock($item['g']);
clock(mb_detect_encoding($item['g']));
//здесь ничего не изменилось и всё те же краказябры
$item['g'] = mb_convert_encoding($item['g'], 'utf-8', mb_detect_encoding($item['g'])); 
$item['f'] = mb_convert_encoding($item['f'], 'utf-8', mb_detect_encoding($item['f']));

Аннотация 2020-05-22 140952

У меня получается так, что оно то выставило CP1252 но после получания данных там всё равно кряказябры которые не получается в нормальные символы конвертировать.

Этим методом я получаю данные с файла.

public static function toArray($filepath)
    {
        $spreadsheet = IOFactory::load($filepath);
        $worksheet = $spreadsheet->getActiveSheet();

        $rows = [];

        foreach ($worksheet->getRowIterator() as $row) {
            $cell_iterator = $row->getCellIterator();
            $cell_iterator->setIterateOnlyExistingCells(false);
            $cells = [];

            foreach ($cell_iterator as $key => $cell) {
                $cells[strtolower($cell->getColumn())] = $cell->getValue();
            }

            $rows[] = $cells;
        }

        return $rows;
    }

@DmitrySkibitsky
Copy link

The problem is relevant at the moment.

I've made a pull request to fix the issue #1484, but as far as I've never made pull requests to any 3rd party libs before, I'm not sure if it is correct or not. Also unfortunately I don't have enough time to add unit tests for this feature now, so I don't know is it acceptable or not.

Anyway you can use my fork until it is merged

А это файл с которым у меня проблемы https://dropmefiles.com/Mvhah

@DmitrySkibitsky
Copy link

The problem is relevant at the moment.

I've made a pull request to fix the issue #1484, but as far as I've never made pull requests to any 3rd party libs before, I'm not sure if it is correct or not. Also unfortunately I don't have enough time to add unit tests for this feature now, so I don't know is it acceptable or not.

Anyway you can use my fork until it is merged

Я вот так изменил код и начало работать.

Аннотация 2020-05-22 143704

Аннотация 2020-05-22 143704ffff

@Torokh
Copy link

Torokh commented Oct 13, 2020

Проблема актуальна на данный момент.

Я сделал запрос на перенос, чтобы исправить проблему № 1484 , но, поскольку я никогда раньше не делал запросы на перенос к каким-либо сторонним библиотекам, я не уверен, правильно это или нет. Также, к сожалению, у меня сейчас недостаточно времени для добавления модульных тестов для этой функции, поэтому я не знаю, приемлемо это или нет.
В любом случае вы можете использовать мою вилку, пока она не будет объединена

Я вот так изменил код и начало работать.

Аннотация 2020-05-22 143704

Аннотация 2020-05-22 143704ffff

А в каком файле Вы это сделали ?

@boltunoreh
Copy link
Contributor Author

Проблема актуальна на данный момент.

Я сделал запрос на перенос, чтобы исправить проблему № 1484 , но, поскольку я никогда раньше не делал запросы на перенос к каким-либо сторонним библиотекам, я не уверен, правильно это или нет. Также, к сожалению, у меня сейчас недостаточно времени для добавления модульных тестов для этой функции, поэтому я не знаю, приемлемо это или нет.
В любом случае вы можете использовать мою вилку, пока она не будет объединена

Я вот так изменил код и начало работать.
Аннотация 2020-05-22 143704
Аннотация 2020-05-22 143704ffff

А в каком файле Вы это сделали ?

my PR was merged, so there is a setter method now, you can use it in your code explicitly:
$reader->setCodepage('CP1251')

@Torokh
Copy link

Torokh commented Oct 13, 2020 via email

@Torokh
Copy link

Torokh commented Oct 13, 2020

Так же и осталось (

$reader      = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xls");
$reader->setCodepage('CP1251');
$spreadsheet = $reader->load("3-ndfl.xls");
$locale = 'ru_ru';
$validLocale = \PhpOffice\PhpSpreadsheet\Settings::setLocale($locale);
$sheets      = $spreadsheet->getSheetCount();

$inn        = $_REQUEST['inn'];

for ($i = 0; $i < strlen($inn); $i++) {
    $spreadsheet->getActiveSheet()->setCellValueExplicit($innCell[$i], $inn[$i], \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
}

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->setPreCalculateFormulas(false);
$writer->save("example1.xls");

@oleibman
Copy link
Collaborator

oleibman commented Jul 3, 2024

Fixed by PR #1484 in June 2020.

@oleibman oleibman removed the stale label Jul 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

4 participants