Text formatting in csv format in excel

Содержание

  1. Import or export text (.txt or .csv) files
  2. Import a text file by opening it in Excel
  3. Import a text file by connecting to it (Power Query)
  4. Export data to a text file by saving it
  5. Import a text file by connecting to it
  6. Export data to a text file by saving it
  7. Need more help?
  8. How to change Excel CSV delimiter to comma or semicolon
  9. What delimiter Excel uses for CSV files
  10. Change separator when saving Excel file as CSV
  11. Change delimiter when importing CSV to Excel
  12. Indicate separator directly in CSV file
  13. Choose delimiter in Text Import Wizard
  14. Specify delimiter when creating a Power Query connection
  15. Change default CSV separator globally
  16. Changing List separator: background and consequences
  17. You may also be interested in

Import or export text (.txt or .csv) files

There are two ways to import data from a text file with Excel: you can open it in Excel, or you can import it as an external data range. To export data from Excel to a text file, use the Save As command and change the file type from the drop-down menu.

There are two commonly used text file formats:

Delimited text files (.txt), in which the TAB character (ASCII character code 009) typically separates each field of text.

Comma separated values text files (.csv), in which the comma character (,) typically separates each field of text.

You can change the separator character that is used in both delimited and .csv text files. This may be necessary to make sure that the import or export operation works the way that you want it to.

Note: You can import or export up to 1,048,576 rows and 16,384 columns.

Import a text file by opening it in Excel

You can open a text file that you created in another program as an Excel workbook by using the Open command. Opening a text file in Excel does not change the format of the file — you can see this in the Excel title bar, where the name of the file retains the text file name extension (for example, .txt or .csv).

Go to File > Open and browse to the location that contains the text file.

Select Text Files in the file type dropdown list in the Open dialog box.

Locate and double-click the text file that you want to open.

If the file is a text file (.txt), Excel starts the Import Text Wizard. When you are done with the steps, click Finish to complete the import operation. See Text Import Wizard for more information about delimiters and advanced options.

If the file is a .csv file, Excel automatically opens the text file and displays the data in a new workbook.

Note: When Excel opens a .csv file, it uses the current default data format settings to interpret how to import each column of data. If you want more flexibility in converting columns to different data formats, you can use the Import Text Wizard. For example, the format of a data column in the .csv file may be MDY, but Excel’s default data format is YMD, or you want to convert a column of numbers that contains leading zeros to text so you can preserve the leading zeros. To force Excel to run the Import Text Wizard, you can change the file name extension from .csv to .txt before you open it, or you can import a text file by connecting to it (for more information, see the following section).

Import a text file by connecting to it (Power Query)

You can import data from a text file into an existing worksheet.

On the Data tab, in the Get & Transform Data group, click From Text/CSV.

In the Import Data dialog box, locate and double-click the text file that you want to import, and click Import.

In the preview dialog box, you have several options:

Select Load if you want to load the data directly to a new worksheet.

Alternatively, select Load to if you want to load the data to a table, PivotTable/PivotChart, an existing/new Excel worksheet, or simply create a connection. You also have the choice of adding your data to the Data Model.

Select Transform Data if you want to load the data to Power Query, and edit it before bringing it to Excel.

If Excel doesn’t convert a particular column of data to the format that you want, then you can convert the data after you import it. For more information, see Convert numbers stored as text to numbers and Convert dates stored as text to dates.

Export data to a text file by saving it

You can convert an Excel worksheet to a text file by using the Save As command.

Go to File > Save As.

In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited).

Note: The different formats support different feature sets. For more information about the feature sets that are supported by the different text file formats, see File formats that are supported in Excel.

Browse to the location where you want to save the new text file, and then click Save.

A dialog box appears, reminding you that only the current worksheet will be saved to the new file. If you are certain that the current worksheet is the one that you want to save as a text file, click OK. You can save other worksheets as separate text files by repeating this procedure for each worksheet.

You may also see an alert below the ribbon that some features might be lost if you save the workbook in a CSV format.

For more information about saving files in other formats, see Save a workbook in another file format.

Import a text file by connecting to it

You can import data from a text file into an existing worksheet.

Click the cell where you want to put the data from the text file.

On the Data tab, in the Get External Data group, click From Text.

In the Import Data dialog box, locate and double-click the text file that you want to import, and click Import.

Follow the instructions in the Text Import Wizard. Click Help on any page of the Text Import Wizard for more information about using the wizard. When you are done with the steps in the wizard, click Finish to complete the import operation.

In the Import Data dialog box, do the following:

Under Where do you want to put the data?, do one of the following:

To return the data to the location that you selected, click Existing worksheet.

To return the data to the upper-left corner of a new worksheet, click New worksheet.

Optionally, click Properties to set refresh, formatting, and layout options for the imported data.

Excel puts the external data range in the location that you specify.

If Excel does not convert a column of data to the format that you want, you can convert the data after you import it. For more information, see Convert numbers stored as text to numbers and Convert dates stored as text to dates.

Export data to a text file by saving it

You can convert an Excel worksheet to a text file by using the Save As command.

Go to File > Save As.

The Save As dialog box appears.

In the Save as type box, choose the text file format for the worksheet.

For example, click Text (Tab delimited) or CSV (Comma delimited).

Note: The different formats support different feature sets. For more information about the feature sets that are supported by the different text file formats, see File formats that are supported in Excel.

Browse to the location where you want to save the new text file, and then click Save.

A dialog box appears, reminding you that only the current worksheet will be saved to the new file. If you are certain that the current worksheet is the one that you want to save as a text file, click OK. You can save other worksheets as separate text files by repeating this procedure for each worksheet.

A second dialog box appears, reminding you that your worksheet may contain features that are not supported by text file formats. If you are interested only in saving the worksheet data into the new text file, click Yes. If you are unsure and would like to know more about which Excel features are not supported by text file formats, click Help for more information.

For more information about saving files in other formats, see Save a workbook in another file format.

The way you change the delimiter when importing is different depending on how you import the text.

If you use Get & Transform Data > From Text/CSV, after you choose the text file and click Import, choose a character to use from the list under Delimiter. You can see the effect of your new choice immediately in the data preview, so you can be sure you make the choice you want before you proceed.

If you use the Text Import Wizard to import a text file, you can change the delimiter that is used for the import operation in Step 2 of the Text Import Wizard. In this step, you can also change the way that consecutive delimiters, such as consecutive quotation marks, are handled.

See Text Import Wizard for more information about delimiters and advanced options.

If you want to use a semi-colon as the default list separator when you Save As .csv, but need to limit the change to Excel, consider changing the default decimal separator to a comma — this forces Excel to use a semi-colon for the list separator. Obviously, this will also change the way decimal numbers are displayed, so also consider changing the Thousands separator to limit any confusion.

Clear Excel Options > Advanced > Editing options > Use system separators.

Set Decimal separator to , (a comma).

Set Thousands separator to . (a period).

When you save a workbook as a .csv file, the default list separator (delimiter) is a comma. You can change this to another separator character using Windows Region settings.

Caution: Changing the Windows setting will cause a global change on your computer, affecting all applications. To only change the delimiter for Excel, see Change the default list separator for saving files as text (.csv) in Excel.

In Microsoft Windows 10, right-click the Start button, and then click Settings.

Click Time & Language, and then click Region in the left panel.

In the main panel, under Regional settings, click Additional date, time, and regional settings.

Under Region, click Change date, time, or number formats.

In the Region dialog, on the Format tab, click Additional settings.

In the Customize Format dialog, on the Numbers tab, type a character to use as the new separator in the List separator box.

In Microsoft Windows, click the Start button, and then click Control Panel.

Under Clock, Language, and Region, click Change date, time, or number formats.

In the Region dialog, on the Format tab, click Additional settings.

In the Customize Format dialog, on the Numbers tab, type a character to use as the new separator in the List separator box.

Note: After you change the list separator character for your computer, all programs use the new character as a list separator. You can change the character back to the default character by following the same procedure.

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Источник

How to change Excel CSV delimiter to comma or semicolon

by Svetlana Cheusheva, updated on March 9, 2023

The tutorial shows how to change CSV separator when importing or exporting data to/from Excel, so you can save your file in the comma-separated values or semicolon-separated values format.

Excel is diligent. Excel is smart. It thoroughly examines the system settings of the machine it’s running on and does its best to anticipate the user’s needs … quite often to disappointing results.

Imagine this: you want to export your Excel data to another application, so you go save it in the CSV format supported by many programs. Whatever CSV option you use, the result is a semicolon-delimited file instead of comma-separated you really wanted. The setting is default, and you have no idea how to change it. Don’t give up! No matter how deep the setting is hidden, we’ll show you a way to locate it and tweak for your needs.

What delimiter Excel uses for CSV files

To handle .csv files, Microsoft Excel uses the List separator defined in Windows Regional settings.

In North America and some other countries, the default list separator is a comma, so you get CSV comma delimited.

In European countries, a comma is reserved for the decimal symbol, and the list separator is generally set to semicolon. That is why the result is CSV semicolon delimited.

To get a CSV file with another field delimiter, apply one of the approaches described below.

Change separator when saving Excel file as CSV

When your save a workbook as a .csv file, Excel separates values with your default List separator. To force it to use a different delimiter, proceed with the following steps:

  1. Click File >Options >Advanced.
  2. Under Editing options, clear the Use system separators check box.
  3. Change the default Decimal separator. As this will change the way decimal numbers are displayed in your worksheets, choose a different Thousands separator to avoid confusion.

Depending on which separator you wish to use, configure the settings in one of the following ways.

To convert Excel file to CSV semicolon delimited, set the default decimal separator to a comma. This will get Excel to use a semicolon for the List separator (CSV delimiter):

  • Set Decimal separator to comma (,)
  • Set Thousands separator to period (.)

To save Excel file as CSV comma delimited, set the decimal separator to a period (dot). This will make Excel use a comma for the List separator (CSV delimiter):

  • Set Decimal separator to period (.)
  • Set Thousands separator to comma (,)

If you want to change a CSV separator only for a specific file, then tick the Use system settings check box again after exporting your Excel workbook to CSV.

Note. Obviously, the changes you’ve made in Excel Options are limited to Excel. Other applications will keep using the default List separator defined in your Windows Regional settings.

Change delimiter when importing CSV to Excel

There are a few different ways to import CSV file into Excel. The way of changing the delimiter depends on the importing method you opted for.

Indicate separator directly in CSV file

For Excel to be able to read a CSV file with a field separator used in a given CSV file, you can specify the separator directly in that file. For this, open your file in any text editor, say Notepad, and type the below string before any other data:

  • To separate values with comma: sep=,
  • To separate values with semicolon: sep=;
  • To separate values with a pipe: sep=|

In a similar fashion, you can use any other character for the delimiter — just type the character after the equality sign.

Once the delimiter is defined, you can open your text file in Excel like you normally would, from Excel itself or from Windows Explorer.

For example, to correctly open a semicolon delimited CSV in Excel, we explicitly indicate that the field separator is a semicolon:

Choose delimiter in Text Import Wizard

Another way to handle a csv file with a delimiter different from the default one is to import the file rather than open. In Excel 2013 an earlier, that was quite easy to do with the Text Import Wizard residing on the Data tab, in the Get External Data group. Beginning with Excel 2016, the wizard is removed from the ribbon as a legacy feature. However, you can still make use of it:

  • Enable From Text (Legacy) feature.
  • Change the file extension from .csv to .txt, and then open the txt file from Excel. This will launch the Import Text Wizard automatically.

In step 2 of the wizard, you are suggested to choose from the predefined delimiters (tab, comma, semicolon, or space) or specify your custom one:

Specify delimiter when creating a Power Query connection

Microsoft Excel 2016 and higher provides one more easy way to import a csv file — by connecting to it with the help of Power Query. When creating a Power Query connection, you can choose the delimiter in the Preview dialog window:

Change default CSV separator globally

To change the default List separator not only for Excel but for all programs installed on your computer, here’s what you need to do:

    On Windows, go to Control Panel >Region settings. For this, just type Region in the Windows search box, and then click Region settings.

In the Region panel, under Related settings, click Additional date, time, and regional settings.

Under Region, click Change date, time, or number formats.

In the Region dialog box, on the Formats tab, click Additional settings

In the Customize Format dialog box, on the Numbers tab, type the character you want to use as the default CSV delimiter in the List separator box.

For this change to work, the List separatorshould not be the same as Decimal symbol.

  • Click OK twice to close both dialog boxes.
  • When done, restart Excel, so it can pick up your changes.

    • Modifying the system settings will cause a global change on your computer that will affect all applications and all output of the system. Do not do this unless you are 100% confident in the results.
    • If changing the separator has adversely affected the behavior of some application or caused other troubles on your machine, undo the changes. For this, click the Reset button in the Customize Format dialog box (step 5 above). This will remove all the customizations you’ve made and restore the system default settings.

    Changing List separator: background and consequences

    Before changing the List separator on your machine, I encourage you to carefully read this section, so you fully understand possible outcomes.

    First off, it should be noted that depending on the country Windows uses different default separators. It’s because large numbers and decimals are written in different ways across the globe.

    In the USA, UK and some other English-speaking countries including Australia and New Zealand, the following separators are used:

    Decimal symbol: dot (.)

    Digit grouping symbol: comma (,)

    List separator: comma (,)

    In most European countries, the default list separator is a semicolon (;) because a comma is utilized as the decimal point:

    Decimal symbol: comma (,)

    Digit grouping symbol: dot (.)

    List separator: semicolon (;)

    For example, here’s how two thousand dollars and fifty cents is written in different countries:

    US and UK: $2,000.50

    How does all this relate to the CSV delimiter? The point is that the List separator (CSV delimiter) and Decimal symbol should be two different characters. That means setting the List separator to comma will require changing the default Decimal symbol (if it’s set to comma). As the result, numbers will be displayed in a different way in all your applications.

    Moreover, List separator is used for separating arguments in Excel formulas. Once you change it, say from comma to semicolon, the separators in all your formulas will also change to semicolons.

    If you are not ready for such large-scale modifications, then change a separator only for a specific CSV file as described in the first part of this tutorial.

    That’s how you can open or save CSV files with different delimiters in Excel. Thank you for reading and see you next week!

    You may also be interested in

    Table of contents

    This is the most recent post on that topic I could find, which tells me, that this problem has still not been SUSTAINABLY resolved by the «software giant» (as one said here) Microsoft .
    The only sustainable way to resolve it — and not the whole world is the United States of America, so we DO NEED such a resolution — would be a seamlessly added EXPORT filter, allowing to replace the the decimal and field separators of the csv saved by Excel .
    Actually this could also be achieved — as a workaround — by a well-crafted VBA macro.
    But we DO NEED this as a built-in function of Excel and this can only be done by Microsoft as the manufacturer of their (international . ) Office suite, right ?
    Remark:
    When writing such a macro (as a workaround), you would not only have to replace , and ;
    Be aware that the csv specification also allows the use of of the separator WITHIN a field, when using special delimiters, like that:
    . , «This is a text, aint it», 64.7, .
    So you would have to take care of such «exceptions», otherwise you’d spoil the whole csv.
    Anyway thanks to all, contributing ideas to this thread, including Svetlana for describing all EXISTING workarounds (which are only a crutch in my opinion; sorry Svetlana, that’s not your fault of course !)

    FINALLY.
    Would anyone of you know where to request such a «feature» at Microsoft directly ?
    Any developers forum we could jointly add such a request and could gather others, who hopefully agree with us and demand such a priority change with their next release ?

    This is rediculous. How can a BIG software giant as Microsoft think in this way!?
    Let us set the separator manually.

    If you look at some other software that import/export CSV they use comma as separator and put all the information within quotes. If there is a quote in the information it is escaped.

    I guess there’s some old standard from 1965 stating how a CSV should be. 🙁

    Hi all, Svetlana is not true at all, but only partially. I will explain.

    If you use English locale and you in Excel change decimal separator from system to comma, Excel understand that he cannot use comma as a field delimiter and will use semicolon instead of it and will save csv file in non-english format, it is for example: 1,5;23,45.

    But, in the case you are working with for example Czech locale (or probably with French locale) and you in Excel change a decimal separator to dot as correct for English csv and save this file. The format of file is for example: 1.5;23;45 and not expected 1.5,23.45. The reason is, I guess, that Excel has no any reason to change a field separator from semicolon to comma, because semicolon is a correct field separator for csv file and and does not contradict with the dot or comma decimal delimiter at all.

    So with English locale you can save an usual non-english csv with comma decimal delimiter and semicolon field separator, but with non-english locale (Czech or French) you cannot save usual English csv, with dot decimal delimiter and comma field separator, but you can save alternative English csv, with dot decimal delimiter and semicolon field separator.

    Of course another possibility is to switch locale with other possible problems, for example with other application.

    Best regards,
    Martin Molhanec

    All works as intended. Microsoft 365 Apps for Enterprise.
    Decimal and Thousands separators can be changed in my case — just mind the emtpy space character that you HAVE to delete!

    [ 0. 0. 0. 1. 7. 6. 0. 0. 0. 0. 0. 2. 4. 1.
    0. 0. 2. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
    0. 0. 0. 0. 0. 0. 0. 34. 128. 106. 6. 0. 23. 4.
    1. 95. 128. 42. 18. 7. 128. 15. 2. 18. 16. 4. 10. 23.
    46. 6. 10. 73. 79. 1. 0. 1. 19. 12. 29. 128. 83. 27.
    10. 5. 29. 7. 3. 23. 82. 128. 128. 25. 128. 71. 13. 15.
    25. 40. 66. 51. 37. 43. 25. 81. 128. 19. 5. 12. 47. 43.
    20. 73. 13. 19. 14. 8. 40. 77. 52. 23. 48. 22. 14. 6.
    5. 38. 31. 37. 78. 29. 4. 1. 37. 36. 56. 81. 20. 9.
    3. 6.];[ 0. 0. 0. 1. 7. 6. 0. 0. 0. 0. 0. 2. 4. 1.
    0. 0. 2. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
    0. 0. 0. 0. 0. 0. 0. 34. 128. 106. 6. 0. 23. 4.
    1. 95. 128. 42. 18. 7. 128. 15. 2. 18. 16. 4. 10. 23.
    46. 6. 10. 73. 79. 1. 0. 1. 19. 12. 29. 128. 83. 27.
    10. 5. 29. 7. 3. 23. 82. 128. 128. 25. 128. 71. 13. 15.
    25. 40. 66. 51. 37. 43. 25. 81. 128. 19. 5. 12. 47. 43.
    20. 73. 13. 19. 14. 8. 40. 77. 52. 23. 48. 22. 14. 6.
    5. 38. 31. 37. 78. 29. 4. 1. 37. 36. 56. 81. 20. 9.
    3. 6.];True

    Please need to make a code or tools to be three above details as a column, its mean [ ] [ ] True as a three columns

    This instruction doesn’t work:
    «To save Excel file as CSV comma delimited, set the decimal separator to a period (dot). This will make Excel use a comma for the List separator (CSV delimiter):»

    I’ve just retested it in my Excel 365 — it does work as described. What Excel version do you use?

    I had the same problem, could not change the list separator modifying it in Excel 2016 Professional. The file I was trying to convert, had to be used in another program that uses the comma as list separator (forScore).
    I confirm the second option, the global change of the list separator. This has the draw-back that it interferes with other simulating programs. So, after converting the file, I had to restore the configuration for my other simulators to work properly again.

    How did you test the first approach?

    Here’s what I did:

    — Performed the steps described in «Change separator when saving Excel file as CSV». In particular, set Decimal separator to period (.) and Thousands separator to comma (,).
    — Saved the workbook as CSV file.
    — Opened the CSV file in Notepad to check which separator is actually used. In my case, the result is always comma-separated values.

    Same story for me.
    And i am not allowed to change global setting by company policy, so no alternative there.

    Hi Svetlana,
    for me with Excel 365 it is not working.
    Allthough doing all steps and chekcing it twice, result is still semicolon separataed.

    The semicolon is still there since perhaps you have missed this part «For this change to work, the List separator should not be the same as Decimal symbol.» on the article.

    If all above do not work and you want to properly read/modify csv which source file has comma as separator and dot as delimiter just open it in an editor, I used vsc for example. Mark all commas in the file, change them to semicolons after that mark all dots if you have numbers and change them to commas.

    Office 365, version 2108. comma delimited doesn’t work for me as well. All done with the description from this article.
    Microsoft it’s shame we cannot do it Excel :/

    Copyright © 2003 – 2023 Office Data Apps sp. z o.o. All rights reserved.

    Microsoft and the Office logos are trademarks or registered trademarks of Microsoft Corporation. Google Chrome is a trademark of Google LLC.

    Источник

    Время на прочтение
    5 мин

    Количество просмотров 197K

    Продукты HFLabs в промышленных объемах обрабатывают данные: адреса, ФИО, реквизиты компаний и еще вагон всего. Естественно, тестировщики ежедневно с этими данными имеют дело: обновляют тест-кейсы, изучают результаты очистки. Часто заказчики дают «живую» базу, чтобы тестировщик настроил сервис под нее.

    Первое, чему мы учим новых QA — сохранять данные в первозданном виде. Все по заветам: «Не навреди». В статье я расскажу, как аккуратно работать с CSV-файлами в Excel и Open Office. Советы помогут ничего не испортить, сохранить информацию после редактирования и в целом чувствовать себя увереннее.

    Материал базовый, профессионалы совершенно точно заскучают.

    Что такое CSV-файлы

    Формат CSV используют, чтобы хранить таблицы в текстовых файлах. Данные очень часто упаковывают именно в таблицы, поэтому CSV-файлы очень популярны.


    CSV-файл состоит из строк с данными и разделителей, которые обозначают границы столбцов

    CSV расшифровывается как comma-separated values — «значения, разделенные запятыми». Но пусть название вас не обманет: разделителями столбцов в CSV-файле могут служить и точки с запятой, и знаки табуляции. Это все равно будет CSV-файл.

    У CSV куча плюсов перед тем же форматом Excel: текстовые файлы просты как пуговица, открываются быстро, читаются на любом устройстве и в любой среде без дополнительных инструментов.

    Из-за своих преимуществ CSV — сверхпопулярный формат обмена данными, хотя ему уже лет 40. CSV используют прикладные промышленные программы, в него выгружают данные из баз.

    Одна беда — текстового редактора для работы с CSV мало. Еще ничего, если таблица простая: в первом поле ID одной длины, во втором дата одного формата, а в третьем какой-нибудь адрес. Но когда поля разной длины и их больше трех, начинаются мучения.


    Следить за разделителями и столбцами — глаза сломаешь

    Еще хуже с анализом данных — попробуй «Блокнотом» хотя бы сложить все числа в столбце. Я уж не говорю о красивых графиках.

    Поэтому CSV-файлы анализируют и редактируют в Excel и аналогах: Open Office, LibreOffice и прочих.

    Ветеранам, которые все же дочитали: ребята, мы знаем об анализе непосредственно в БД c помощью SQL, знаем о Tableau и Talend Open Studio. Это статья для начинающих, а на базовом уровне и небольшом объеме данных Excel с аналогами хватает.

    Как Excel портит данные: из классики

    Все бы ничего, но Excel, едва открыв CSV-файл, начинает свои лукавые выкрутасы. Он без спроса меняет данные так, что те приходят в негодность. Причем делает это совершенно незаметно. Из-за этого в свое время мы схватили ворох проблем.

    Большинство казусов связано с тем, что программа без спроса преобразует строки с набором цифр в числа.

    Округляет. Например, в исходной ячейке два телефона хранятся через запятую без пробелов: «5235834,5235835». Что сделает Excel? Лихо превратит номера́ в одно число и округлит до двух цифр после запятой: «5235834,52». Так мы потеряем второй телефон.

    Приводит к экспоненциальной форме. Excel заботливо преобразует «123456789012345» в число «1,2E+15». Исходное значение потеряем напрочь.

    Проблема актуальна для длинных, символов по пятнадцать, цифровых строк. Например, КЛАДР-кодов (это такой государственный идентификатор адресного объекта: го́рода, у́лицы, до́ма).

    Удаляет лидирующие плюсы. Excel считает, что плюс в начале строки с цифрами — совершенно лишний символ. Мол, и так ясно, что число положительное, коль перед ним не стоит минус. Поэтому лидирующий плюс в номере «+74955235834» будет отброшен за ненадобностью — получится «74955235834». (В реальности номер пострадает еще сильнее, но для наглядности обойдусь плюсом).

    Потеря плюса критична, например, если данные пойдут в стороннюю систему, а та при импорте жестко проверяет формат.

    Разбивает по три цифры. Цифровую строку длиннее трех символов Excel, добрая душа, аккуратно разберет. Например, «8 495 5235834» превратит в «84 955 235 834».

    Форматирование важно как минимум для телефонных номеров: пробелы отделяют коды страны и города от остального номера и друг от друга. Excel запросто нарушает правильное членение телефона.

    Удаляет лидирующие нули. Строку «00523446» Excel превратит в «523446».
    А в ИНН, например, первые две цифры — это код региона. Для Республики Алтай он начинается с нуля — «04». Без нуля смысл номера исказится, а проверку формата ИНН вообще не пройдет.

    Меняет даты под локальные настройки. Excel с удовольствием исправит номер дома «1/2» на «01.фев». Потому что Windows подсказал, что в таком виде вам удобнее считывать даты.

    Побеждаем порчу данных правильным импортом

    Если серьезно, в бедах виноват не Excel целиком, а неочевидный способ импорта данных в программу.

    По умолчанию Excel применяет к данным в загруженном CSV-файле тип «General» — общий. Из-за него программа распознает цифровые строки как числа. Такой порядок можно победить, используя встроенный инструмент импорта.

    Запускаю встроенный в Excel механизм импорта. В меню это «Data → Get External Data → From Text».

    Выбираю CSV-файл с данными, открывается диалог. В диалоге кликаю на тип файла Delimited (с разделителями). Кодировка — та, что в файле, обычно определяется автоматом. Если первая строка файла — шапка, отмечаю «My Data Has Headers».

    Перехожу ко второму шагу диалога. Выбираю разделитель полей (обычно это точка с запятой — semicolon). Отключаю «Treat consecutive delimiters as one», а «Text qualifier» выставляю в «{none}». (Text qualifier — это символ начала и конца текста. Если разделитель в CSV — запятая, то text qualifier нужен, чтобы отличать запятые внутри текста от запятых-разделителей.)

    На третьем шаге выбираю формат полей, ради него все и затевалось. Для всех столбцов выставляю тип «Text». Кстати, если кликнуть на первую колонку, зажать шифт и кликнуть на последнюю, выделятся сразу все столбцы. Удобно.

    Дальше Excel спросит, куда вставлять данные из CSV — можно просто нажать «OK», и данные появятся в открытом листе.


    Перед импортом придется создать в Excel новый workbook

    Но! Если я планирую добавлять данные в CSV через Excel, придется сделать еще кое-что.

    После импорта нужно принудительно привести все-все ячейки на листе к формату «Text». Иначе новые поля приобретут все тот же тип «General».

    • Нажимаю два раза Ctrl+A, Excel выбирает все ячейки на листе;
    • кликаю правой кнопкой мыши;
    • выбираю в контекстном меню «Format Cells»;
    • в открывшемся диалоге выбираю слева тип данных «Text».


    Чтобы выделить все ячейки, нужно нажать Ctrl+A два раза. Именно два, это не шутка, попробуйте

    После этого, если повезет, Excel оставит исходные данные в покое. Но это не самая твердая гарантия, поэтому мы после сохранения обязательно проверяем файл через текстовый просмотрщик.

    Альтернатива: Open Office Calc

    Для работы с CSV-файлами я использую именно Calc. Он не то чтобы совсем не считает цифровые данные строками, но хотя бы не применяет к ним переформатирование в соответствии с региональными настройками Windows. Да и импорт попроще.

    Конечно, понадобится пакет Open Office (OO). При установке он предложит переназначить на себя файлы MS Office. Не рекомендую: хоть OO достаточно функционален, он не до конца понимает хитрое микрософтовское форматирование документов.

    А вот назначить OO программой по умолчанию для CSV-файлов — вполне разумно. Сделать это можно после установки пакета.

    Итак, запускаем импорт данных из CSV. После двойного клика на файле Open Office показывает диалог.


    Заметьте, в OO не нужно создавать новый воркбук и принудительно запускать импорт, все само

    1. Кодировка — как в файле.
    2. «Разделитель» — точка с запятой. Естественно, если в файле разделителем выступает именно она.
    3. «Разделитель текста» — пустой (все то же, что в Excel).
    4. В разделе «Поля» кликаю в левый-верхний квадрат таблицы, подсвечиваются все колонки. Указываю тип «Текст».

    Штука, которая испортила немало крови: если по ошибке выбрать несколько разделителей полей или не тот разделитесь текста, файл может правильно открыться, но неправильно сохраниться.

    Помимо Calc у нас в HFLabs популярен libreOffice, особенно под «Линуксом». И то, и другое для CSV применяют активнее, чем Excel.

    Бонус-трек: проблемы при сохранении из Calc в .xlsx

    Если сохраняете данные из Calc в экселевский формат .xlsx, имейте в виду — OO порой необъяснимо и масштабно теряет данные.


    Белая пустошь, раскинувшаяся посередине, в оригинальном CSV-файле богато заполнена данными

    Поэтому после сохранения я еще раз открываю файл и убеждаюсь, что данные на месте.

    Если что-то потерялись, лечение — пересохранить из CSV в .xlsx. Или, если установлен Windows, импортнуть из CSV в Excel и сохранить оттуда.

    После пересохранения обязательно еще раз проверяю, что все данные на месте и нет лишних пустых строк.

    Если интересно работать с данными, посмотрите на наши вакансии. HFLabs почти всегда нужны аналитики, тестировщики, инженеры по внедрению, разработчики. Данными обеспечим так, что мало не покажется :)

    Import or export text (.txt or .csv) files

    There are two ways to import data from a text file with Excel: you can open it in Excel, or you can import it as an external data range. To export data from Excel to a text file, use the Save As command and change the file type from the drop-down menu.

    There are two commonly used text file formats:

    • Delimited text files (.txt), in which the TAB character (ASCII character code 009) typically separates each field of text.

    • Comma separated values text files (.csv), in which the comma character (,) typically separates each field of text.

    You can change the separator character that is used in both delimited and .csv text files. This may be necessary to make sure that the import or export operation works the way that you want it to.

    Note: You can import or export up to 1,048,576 rows and 16,384 columns.

    Import a text file by opening it in Excel

    You can open a text file that you created in another program as an Excel workbook by using the Open command. Opening a text file in Excel does not change the format of the file — you can see this in the Excel title bar, where the name of the file retains the text file name extension (for example, .txt or .csv).

    1. Go to File > Open and browse to the location that contains the text file.

    2. Select Text Files in the file type dropdown list in the Open dialog box.

    3. Locate and double-click the text file that you want to open.

      • If the file is a text file (.txt), Excel starts the Import Text Wizard. When you are done with the steps, click Finish to complete the import operation. See Text Import Wizard for more information about delimiters and advanced options.

      • If the file is a .csv file, Excel automatically opens the text file and displays the data in a new workbook.

        Note: When Excel opens a .csv file, it uses the current default data format settings to interpret how to import each column of data. If you want more flexibility in converting columns to different data formats, you can use the Import Text Wizard. For example, the format of a data column in the .csv file may be MDY, but Excel’s default data format is YMD, or you want to convert a column of numbers that contains leading zeros to text so you can preserve the leading zeros. To force Excel to run the Import Text Wizard, you can change the file name extension from .csv to .txt before you open it, or you can import a text file by connecting to it (for more information, see the following section).

    Import a text file by connecting to it (Power Query)

    You can import data from a text file into an existing worksheet.

    1. On the Data tab, in the Get & Transform Data group, click From Text/CSV.

    2. In the Import Data dialog box, locate and double-click the text file that you want to import, and click Import.

    3. In the preview dialog box, you have several options:

      • Select Load if you want to load the data directly to a new worksheet.

      • Alternatively, select Load to if you want to load the data to a table, PivotTable/PivotChart, an existing/new Excel worksheet, or simply create a connection. You also have the choice of adding your data to the Data Model.

      • Select Transform Data if you want to load the data to Power Query, and edit it before bringing it to Excel.

    If Excel doesn’t convert a particular column of data to the format that you want, then you can convert the data after you import it. For more information, see Convert numbers stored as text to numbers and Convert dates stored as text to dates.

    Export data to a text file by saving it

    You can convert an Excel worksheet to a text file by using the Save As command.

    1. Go to File > Save As.

    2. Click Browse.

    3. In the Save As dialog box, under Save as type box, choose the text file format for the worksheet; for example, click Text (Tab delimited) or CSV (Comma delimited).

      Note: The different formats support different feature sets. For more information about the feature sets that are supported by the different text file formats, see File formats that are supported in Excel.

    4. Browse to the location where you want to save the new text file, and then click Save.

    5. A dialog box appears, reminding you that only the current worksheet will be saved to the new file. If you are certain that the current worksheet is the one that you want to save as a text file, click OK. You can save other worksheets as separate text files by repeating this procedure for each worksheet.

      You may also see an alert below the ribbon that some features might be lost if you save the workbook in a CSV format.

    For more information about saving files in other formats, see Save a workbook in another file format.

    Import a text file by connecting to it

    You can import data from a text file into an existing worksheet.

    1. Click the cell where you want to put the data from the text file.

    2. On the Data tab, in the Get External Data group, click From Text.

    3. In the Import Data dialog box, locate and double-click the text file that you want to import, and click Import.

      Follow the instructions in the Text Import Wizard. Click Help button image on any page of the Text Import Wizard for more information about using the wizard. When you are done with the steps in the wizard, click Finish to complete the import operation.

    4. In the Import Data dialog box, do the following:

      1. Under Where do you want to put the data?, do one of the following:

        • To return the data to the location that you selected, click Existing worksheet.

        • To return the data to the upper-left corner of a new worksheet, click New worksheet.

      2. Optionally, click Properties to set refresh, formatting, and layout options for the imported data.

      3. Click OK.

        Excel puts the external data range in the location that you specify.

    If Excel does not convert a column of data to the format that you want, you can convert the data after you import it. For more information, see Convert numbers stored as text to numbers and Convert dates stored as text to dates.

    Export data to a text file by saving it

    You can convert an Excel worksheet to a text file by using the Save As command.

    1. Go to File > Save As.

    2. The Save As dialog box appears.

    3. In the Save as type box, choose the text file format for the worksheet.

      • For example, click Text (Tab delimited) or CSV (Comma delimited).

      • Note: The different formats support different feature sets. For more information about the feature sets that are supported by the different text file formats, see File formats that are supported in Excel.

    4. Browse to the location where you want to save the new text file, and then click Save.

    5. A dialog box appears, reminding you that only the current worksheet will be saved to the new file. If you are certain that the current worksheet is the one that you want to save as a text file, click OK. You can save other worksheets as separate text files by repeating this procedure for each worksheet.

    6. A second dialog box appears, reminding you that your worksheet may contain features that are not supported by text file formats. If you are interested only in saving the worksheet data into the new text file, click Yes. If you are unsure and would like to know more about which Excel features are not supported by text file formats, click Help for more information.

    For more information about saving files in other formats, see Save a workbook in another file format.

    The way you change the delimiter when importing is different depending on how you import the text.

    • If you use Get & Transform Data > From Text/CSV, after you choose the text file and click Import, choose a character to use from the list under Delimiter. You can see the effect of your new choice immediately in the data preview, so you can be sure you make the choice you want before you proceed.

    • If you use the Text Import Wizard to import a text file, you can change the delimiter that is used for the import operation in Step 2 of the Text Import Wizard. In this step, you can also change the way that consecutive delimiters, such as consecutive quotation marks, are handled.

      See Text Import Wizard for more information about delimiters and advanced options.

    If you want to use a semi-colon as the default list separator when you Save As .csv, but need to limit the change to Excel, consider changing the default decimal separator to a comma — this forces Excel to use a semi-colon for the list separator. Obviously, this will also change the way decimal numbers are displayed, so also consider changing the Thousands separator to limit any confusion.

    1. Clear Excel Options > Advanced > Editing options > Use system separators.

    2. Set Decimal separator to , (a comma).

    3. Set Thousands separator to . (a period).

    When you save a workbook as a .csv file, the default list separator (delimiter) is a comma. You can change this to another separator character using Windows Region settings. 

    Caution: Changing the Windows setting will cause a global change on your computer, affecting all applications. To only change the delimiter for Excel, see Change the default list separator for saving files as text (.csv) in Excel.

    1. In Microsoft Windows 10, right-click the Start button, and then click Settings.

    2. Click Time & Language, and then click Region in the left panel.

    3. In the main panel, under Regional settings, click Additional date, time, and regional settings.

    4. Under Region, click Change date, time, or number formats.

    5. In the Region dialog, on the Format tab, click Additional settings.

    6. In the Customize Format dialog, on the Numbers tab, type a character to use as the new separator in the List separator box.

    7. Click OK twice.

    1. In Microsoft Windows, click the Start button, and then click Control Panel.

    2. Under Clock, Language, and Region, click Change date, time, or number formats.

    3. In the Region dialog, on the Format tab, click Additional settings.

    4. In the Customize Format dialog, on the Numbers tab, type a character to use as the new separator in the List separator box.

    5. Click OK twice.

    Note:  After you change the list separator character for your computer, all programs use the new character as a list separator. You can change the character back to the default character by following the same procedure.

    Need more help?

    You can always ask an expert in the Excel Tech Community or get support in the Answers community.

    See Also

    Import data from external data sources (Power Query)

    Need more help?

    Want more options?

    Explore subscription benefits, browse training courses, learn how to secure your device, and more.

    Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

    Click the Data tab, and select From Text.

    1. Find your CSV file stored on your computer, and click Open.
    2. In the Text Import Wizard window, be sure Delimited is selected as your file type.
    3. In the File origin drop down, select 65001 : Unicode (UTF-8).
    4. Check the My Data has headers box.
    5. Click the Next button.

    Contents

    • 1 How do I edit data in a CSV file?
    • 2 How do I open and edit a CSV file?
    • 3 How do I edit a CSV file in Notepad?
    • 4 How do I convert a CSV file to Excel?
    • 5 How do I edit csv without formatting?
    • 6 How can I edit a csv file online?
    • 7 How do you edit imported data in Excel?
    • 8 How do I open a csv file without Excel?
    • 9 Can Notepad ++ edit CSV?
    • 10 Can I open CSV in notepad?
    • 11 How do I open a CSV file in Notepad?
    • 12 Can you edit a CSV file in Excel?
    • 13 How do I change a CSV file to delimiter in Excel?
    • 14 How do I format a csv file?
    • 15 How read and edit csv file in Java?
    • 16 What is the difference between a CSV and Excel file?
    • 17 How do I edit a CSV file on a Mac?
    • 18 How do I open a CSV file in Excel?
    • 19 What reads CSV files?
    • 20 Which tab enables you to edit an imported .CSV file in Excel?

    How do I edit data in a CSV file?

    Open the CSV file in Microsoft Excel or a compatible application, such as a text editor or Notepad. Move your cursor to an empty line and type an H in column A. Press the Tab key to move to the next column and enter the value that you want to import for that field. Repeat step b for all the fields in the row.

    How do I open and edit a CSV file?

    How to open a CSV in a text editor

    1. Open a text editor like Windows Notepad or TextEdit.
    2. Click “File” and then “Open.”
    3. In the “File Open” dialog box, click the drop-down menu to the right of the “File name” field. If it’s currently set to “Text Documents,” change it to “All Files.”
    4. Find the CSV file and select it.

    How do I edit a CSV file in Notepad?

    Find the CSV file in Windows Explorer. Use the context (right click) menu and select “Edit with Notepad++”. Then you can edit and save the file.

    How do I convert a CSV file to Excel?

    To format in Microsoft Excel, do the following:

    1. Open Microsoft Excel.
    2. Click File > New Workbook in Excel’s top toolbar.
    3. Click From Text in the Data tab.
    4. Select the desired .
    5. Click Get Data.
    6. Select the radio button next to Delimited in the Text Import Wizard.
    7. Click Next.
    8. Select the appropriate Delimiters.

    How do I edit csv without formatting?

    You need to Open an empty Excel and use the import from text option from the DATA tab. There you will have an import wizard, where you can select codification, delimitators and format of each column before importing. After edit, you can save as CSV.

    How can I edit a csv file online?

    How to view, edit, download CSV files online using GroupDocs. Editor App

    1. Click inside the file drop area to upload a CSV file or drag & drop a file.
    2. File will be automatically rendered for you to view/edit/download instantly.
    3. View & edit document.
    4. Download the original CSV file.
    5. Download the edited CSV file.

    How do you edit imported data in Excel?

    How to Edit an Imported Workbook in Excel

    1. Delete unnecessary columns.
    2. Delete unnecessary rows.
    3. Resize columns.
    4. Resize rows.
    5. Erase unneeded cell contents.
    6. Format numeric values.
    7. Copying worksheet data.
    8. Moving worksheet data.

    How do I open a csv file without Excel?

    Go to Data >> Get External Data >> From Text.

    1. Go to the location of the CSV file, that you want to import.
    2. Choose Delimited,
    3. Click next to display the second step of Text Import Wizard.
    4. Click next to move to the third step.
    5. Select the General column and click the Advanced…
    6. Click OK and then Finish.
    7. This is the result.

    Can Notepad ++ edit CSV?

    Notepad++ is particularly ideal for quickly editing and changing data in CSV files, but it’s also amazing for editing HTML, CSS, TXT – or any other type of file that can be opened and edited as text.

    Can I open CSV in notepad?

    Answer: You can open the CSV file on Google Sheet, Notepad, or OpenOffice Calc. Just right-click on the file, select Open With and pick either OpenOffice Calc or Notepad. To open in Google Sheets, go to the File option in Google Sheet, click import, select the CSV file you want to open, click import.

    How do I open a CSV file in Notepad?

    Click the Text Documents drop-down menu at the bottom-right corner of the window, then click All Files. Locate the CSV file to open in Notepad, then double-click it to open it.

    Can you edit a CSV file in Excel?

    While Microsoft Excel allows you to manipulate CSV files, Excel is not a dedicated CSV editor.

    How do I change a CSV file to delimiter in Excel?

    Solution

    1. Make sure Microsoft Excel is closed before trying to change the CSV delimiter.
    2. Open Control Panel.
    3. Next, you need to access Regional Settings.
    4. Click the “Additional Settings” -button.
    5. Find the “List separator” and change it to your preferred delimiter such as a pipe (“|”).

    How do I format a csv file?

    Here are the rules for creating CSV files:

    1. Separate data fields with a delimiter, usually a comma.
    2. Keep each record on a separate line.
    3. Do not follow the last record in a file with a carriage return.
    4. In the first line of the file, include a header with a list of the column names in the file.

    How read and edit csv file in Java?

    Reading and Writing CSVs in Java

    1. Use FileReader to open the CSV file.
    2. Create a BufferedReader and read the file line by line until an “End of File” (EOF) character is reached.
    3. Use the String. split() method to identify the comma delimiter and split the row into fields.

    What is the difference between a CSV and Excel file?

    The difference between CSV and XLS file formats is that CSV format is a plain text format in which values are separated by commas (Comma Separated Values), while XLS file format is an Excel Sheets binary file format which holds information about all the worksheets in a file, including both content and formatting.

    How do I edit a CSV file on a Mac?

    How to Edit CSV File Format on a Mac

    1. Launch Microsoft Word.
    2. Open the “Edit” menu, locate its “Find” submenu and choose “Advanced Find and Replace.” Click on the “Replace” tab and type the text you want to replace in the Find What entry field.

    How do I open a CSV file in Excel?

    Open CSV Files in Microsoft Excel the Right Way

    1. Open a New Excel Document, or open a new worksheet in your existing Excel workbook.
    2. Navigate to the “Data” tab.
    3. Click on the “From Text” button.
    4. Navigate to the folder holding the .
    5. Click “Import.”
    6. The Text Import Wizard will open.
    7. Click “Next.”

    What reads CSV files?

    A CSV file can be opened in any program, however, for most users, a CSV file is best viewed through a spreadsheet program, such as Microsoft Excel, OpenOffice Calc, or Google Docs. If you do not have a spreadsheet program installed on your computer, consider using an online spreadsheet.

    Which tab enables you to edit an imported .CSV file in Excel?

    To import a CSV file into Excel,

    1. Open a new document in Excel first, without opening your file.
    2. Go to the Data tab and select From Text.
    3. Select your file in the Import Text File dialog window and then select Import.
    4. In the Text Import Wizard window, confirm the following selections:
    5. Select Next.

    Win XP, Excel 2007

    I know there are various other posts on csv formatting but couldn’t quite find what i needed.

    Some of our data is held off site by another company and they send us a csv file every morning with the previous days data.

    The problem is this data has come from web input forms that may have drop-down lists.

    For example there may be a drop down list of Number of Employees with options like 1-10, 11-25, 26-50 etc

    When we open the csv file in Excel certain options like 1-10 has been turned into Oct-01 date format which we do not want.

    Is there an easy way to change these back OR reformat the cells and do a find…replace? (This didn’t seem to work terribly well as it kept reverting back to the date)

    Indeed is there a better way of opening the csv file to keep the formatting intact? and save us doing lots of find…replaces.

    Ultimately we will need to open the csv in Excel though.

    Grateful for any hints

    asked Apr 26, 2011 at 9:33

    knookie's user avatar

    1

    Isn’t that SO annoying? Here’s how I deal with this issue:

    When you open the CSV file in Excel, you should get a dialog with parsing options. First you select delimited or fixed then you get a screen that previews the data parsing.

    It’s easy to miss, but in the upper right corner of the dialog box there’s an option to set a specific data format for each column. Select the column you want to protect and set the format to text. (This keeps Excel from dropping the leading zeros in ZIP codes for New England too!)

    Once you get it into Excel, you can do a vlookup or replace to reset the values to your own codes.

    Hope this helps. Good luck.

    answered Apr 28, 2011 at 15:08

    Katherine Chalmers's user avatar

    1

    CSV (Comma Separated Values) – распространённый формат для хранения табличных данных (числовых и текстовых) в виде простого текста. Этот формат файлов популярен и живуч благодаря тому, что огромное количество программ и приложений понимают CSV, хотя бы как альтернативный вариант файлового формата для импорта / экспорта. Более того, формат CSV позволяет пользователю заглянуть в файл и немедленно найти проблему с данными, если таковая имеется, изменить разделитель CSV, правила цитирования и так далее. Это возможно потому, что CSV – это простой текст, и даже не очень опытный пользователь, сможет легко его понять без специальной подготовки.

    В этой статье мы изучим быстрые и эффективные способы экспорта данных из Excel в CSV и узнаем, как преобразовать файл Excel в CSV, сохранив без искажений все специальные и иностранные символы. Описанные в статье приёмы работают во всех версиях Excel 2013, 2010 и 2007.

    • Преобразуем данные из формата Excel в CSV
    • Экспортируем из Excel в формат CSV UTF-8 или UTF-16
    • Другие способы преобразования из формата Excel в CSV (сохраняя специальные символы)

    Содержание

    1. Как преобразовать файл Excel в CSV
    2. Экспортируем из Excel в CSV с кодировкой UTF-8 или UTF-16
    3. Как преобразовать файл Excel в CSV UTF-8
    4. Как преобразовать файл Excel в CSV UTF-16
    5. Другие способы преобразования файлов Excel в CSV
    6. Преобразуем файл Excel в CSV при помощи Таблиц Google
    7. Сохраняем файл .xlsx как .xls и затем преобразуем в файл CSV
    8. Сохраняем файл Excel как CSV при помощи OpenOffice

    Как преобразовать файл Excel в CSV

    Если требуется экспортировать файл Excel в какое-либо другое приложение, например, в адресную книгу Outlook или в базу данных Access, предварительно преобразуйте лист Excel в файл CSV, а затем импортируйте файл .csv в другое приложение. Ниже дано пошаговое руководство, как экспортировать рабочую книгу Excel в формат CSV при помощи инструмента Excel – «Сохранить как».

    1. В рабочей книге Excel откройте вкладку Файл (File) и нажмите Сохранить как (Save as). Кроме этого, диалоговое окно Сохранение документа (Save as) можно открыть, нажав клавишу F12.Преобразование Excel в CSV
    2. В поле Тип файла (Save as type) выберите CSV (разделители – запятые) (CSV (Comma delimited)).Преобразование Excel в CSVКроме CSV (разделители – запятые), доступны несколько других вариантов формата CSV:
      • CSV (разделители – запятые) (CSV (Comma delimited)). Этот формат хранит данные Excel, как текстовый файл с разделителями запятыми, и может быть использован в другом приложении Windows и в другой версии операционной системы Windows.
      • CSV (Macintosh). Этот формат сохраняет книгу Excel, как файл с разделителями запятыми для использования в операционной системе Mac.
      • CSV (MS-DOS). Сохраняет книгу Excel, как файл с разделителями запятыми для использования в операционной системе MS-DOS.
      • Текст Юникод (Unicode Text (*txt)). Этот стандарт поддерживается почти во всех существующих операционных системах, в том числе в Windows, Macintosh, Linux и Solaris Unix. Он поддерживает символы почти всех современных и даже некоторых древних языков. Поэтому, если книга Excel содержит данные на иностранных языках, то рекомендую сначала сохранить её в формате Текст Юникод (Unicode Text (*txt)), а затем преобразовать в CSV, как описано далее в разделе Экспортируем из Excel в формат CSV UTF-8 или UTF-16.

    Замечание: Все упомянутые форматы сохраняют только активный лист Excel.

    1. Выберите папку для сохранения файла в формате CSV и нажмите Сохранить (Save).После нажатия Сохранить (Save) появятся два диалоговых окна. Не переживайте, эти сообщения не говорят об ошибке, так и должно быть.
    2. Первое диалоговое окно напоминает о том, что В файле выбранного типа может быть сохранён только текущий лист (The selected file type does not support workbooks that contain multiple sheets). Чтобы сохранить только текущий лист, достаточно нажать ОК.Преобразование Excel в CSVЕсли нужно сохранить все листы книги, то нажмите Отмена (Cancel) и сохраните все листы книги по-отдельности с соответствующими именами файлов, или можете выбрать для сохранения другой тип файла, поддерживающий несколько страниц.
    3. После нажатия ОК в первом диалоговом окне, появится второе, предупреждающее о том, что некоторые возможности станут недоступны, так как не поддерживаются форматом CSV. Так и должно быть, поэтому просто жмите Да (Yes).Преобразование Excel в CSV

    Вот так рабочий лист Excel можно сохранить как файл CSV. Быстро и просто, и вряд ли тут могут возникнуть какие-либо трудности.

    Экспортируем из Excel в CSV с кодировкой UTF-8 или UTF-16

    Если на листе Excel содержатся какие-либо специальные или иностранные символы (тильда, ударение и подобные) или иероглифы, то преобразование листа Excel в CSV описанным выше способом не сработает.

    Дело в том, что команда Сохранить как > CSV (Save as > CSV) исказит все символы, кроме ASCII (American Standard Code for Information Interchange). И если на листе Excel есть парные кавычки или длинные тире (перенесённые в Excel, например, из документа Word при копировании / вставке текста) – такие символы также будут искромсаны.

    Простое решение – сохранить лист Excel как текстовый файл Unicode(.txt), и затем преобразовать его в CSV. Таким образом все символы, не входящие в ASCII, останутся в целости и сохранности.

    Прежде чем двинуться дальше, позвольте мне кратко пояснить главные отличия между кодировками UTF-8 и UTF-16, чтобы в каждом индивидуальном случае Вы могли выбрать подходящий формат:

    • UTF-8 – это более компактная кодировка, использующая для каждого символа от 1 до 4 байт. Чаще всего рекомендуется использовать этот формат, когда символы ASCII преобладают в файле, т.к. большинство таких символов требует 1 байт памяти. Ещё одно преимущество в том, что кодировка файла UTF-8, содержащего только символы ASCII, ничем не будет отличаться от такого же ASCII-файла.
    • UTF-16 использует от 2 до 4 байт для хранения каждого символа. Учтите, что не во всех случаях файл UTF-16 требует больше места в памяти, чем файл UTF-8. Например, японские символы занимают от 3 до 4 байт в UTF-8 и от 2 до 4 байт в UTF-16. Таким образом, есть смысл использовать UTF-16, если данные содержат азиатские символы, в том числе Японские, Китайские и Корейские. Существенный недостаток этой кодировки в том, что она не полностью совместима с ASCII-файлами и требуются специальные программы для отображения таких файлов. Помните об этом, если планируете импортировать получившиеся файлы из Excel куда-то ещё.

    Как преобразовать файл Excel в CSV UTF-8

    Предположим, у нас есть лист Excel с иностранными символами, в нашем примере – это японские имена.

    Преобразование Excel в CSV

    Чтобы экспортировать этот лист Excel в файл CSV, сохранив при этом все иероглифы, сделаем следующее:

    1. В Excel откройте вкладку Файл (File) и нажмите Сохранить как (Save as).
    2. Введите имя файла, в поле Тип файла (Save as type) выберите Текст Юникод (Unicode Text (*.txt)) и нажмите Сохранить (Save).Преобразование Excel в CSV
    3. Откройте созданный файл в любом стандартном текстовом редакторе, например, в Блокноте.

    Замечание: Не все простые текстовые редакторы полностью поддерживают символы Юникод, поэтому некоторые из них могут отображаться как прямоугольники. В большинстве случаев, это никак не повлияет на итоговый файл, и можно просто не обращать на это внимание или выбрать более продвинутый редактор, например, Notepad++.

    1. Так как в нашем текстовом Юникод файле в качестве разделителей используется символ табуляции, а мы хотим преобразовать его в CSV (разделители – запятые), то необходимо заменить символы табуляции на запятые.

    Замечание: Если нет строгой необходимости получить файл именно с разделителями – запятыми, а нужен любой файл CSV, который Excel сможет понять, то этот шаг можно пропустить, так как Microsoft Excel отлично понимает файлы с разделителем – табуляцией.

    1. Если всё же нужен файл CSV (разделители – запятые), то выполните в Блокноте следующие действия:

      В Блокноте результат будет приблизительно вот такой:

      Преобразование Excel в CSV

    2. Кликните Файл > Сохранить как (File > Save as), введите имя для файла и в выпадающем списке Кодировка (Encoding) выберите UTF-8. Затем нажмите кнопку Сохранить (Save).Преобразование Excel в CSV
    3. Запустите Проводник Windows и измените расширение файла с .txt на .csv.По-другому изменить расширение .txt на .csv можно непосредственно в Блокноте. Для этого в диалоговом окне Сохранить как (Save as) в поле Тип файла (Save as type) выберите вариант Все файлы (All files), а к имени файла в соответствующем поле добавьте «.csv», как показано на рисунке ниже.Преобразование Excel в CSV
    4. Откройте файл CSV в Excel, для этого на вкладке Файл (File) нажмите Открыть > Текстовые файлы (Open > Text files) и проверьте в порядке ли данные.

    Замечание: Если Ваш файл предназначен для использования за пределами Excel и формат UTF-8 является обязательным требованием, то не совершайте на листе никаких изменений и не сохраняйте его снова в Excel, поскольку это может привести к проблемам с чтением кодировки. Если какая-то часть данных не отображается в Excel, откройте тот же файл в Блокноте и в нём внесите исправления в данные. Не забудьте снова сохранить файл в формате UTF-8.

    Как преобразовать файл Excel в CSV UTF-16

    Экспортировать в файл CSV UTF-16 намного быстрее и проще, чем в UTF-8. Дело в том, что Excel автоматически применяет формат UTF-16 при сохранении файла как Текст Юникод (Unicode Text).

    Для этого сохраняем файл при помощи инструмента Сохранить как (Save as) в Excel и затем в Проводнике Windows изменяем расширение созданного файла на .csv. Готово!

    Если нужен файл CSV с запятой или точкой с запятой в качестве разделителя, замените все символы табуляции на запятые или точки с запятой соответственно в Блокноте или в любом другом текстовом редакторе на свой выбор (ранее в этой статье есть подробная инструкция, как это делается).

    Другие способы преобразования файлов Excel в CSV

    Описанные выше способы экспорта данных из Excel в CSV (UTF-8 и UTF-16) универсальны, т.е. подойдут для работы с любыми специальными символами и в любой версии Excel от 2003 до 2013.

    Существует множество других способов преобразования данных из формата Excel в CSV. В отличие от показанных выше решений, эти способы не будут давать в результате чистый UTF-8 файл (это не касается OpenOffice, который умеет экспортировать файлы Excel в несколько вариантов кодировки UTF). Но в большинстве случаев получившийся файл будет содержать правильный набор символов, который далее можно безболезненно преобразовать в формат UTF-8 при помощи любого текстового редактора.

    Преобразуем файл Excel в CSV при помощи Таблиц Google

    Как оказалось, можно очень просто преобразовать файл Excel в CSV при помощи Таблиц Google. При условии, что на Вашем компьютере уже установлен Google Drive, выполните следующие 5 простых шагов:

    1. В Google Drive нажмите кнопку Создать (Create) и выберите Таблица (Spreadsheet).
    2. В меню Файл (File) нажмите Импорт (Import).Преобразование Excel в CSV
    3. Кликните Загрузка (Upload) и выберите файл Excel для загрузки со своего компьютера.
    4. В диалоговом окне Импорт файла (Import file) выберите Заменить таблицу (Replace spreadsheet) и нажмите Импорт (Import).Преобразование Excel в CSV

    Совет: Если файл Excel относительно небольшой, то для экономии времени можно перенести из него данные в таблицу Google при помощи копирования / вставки.

    1. В меню Файл (File) нажмите Скачать как (Download as), выберите тип файла CSV – файл будет сохранён на компьютере.Преобразование Excel в CSV

    В завершение откройте созданный CSV-файл в любом текстовом редакторе, чтобы убедиться, что все символы сохранены правильно. К сожалению, файлы CSV, созданные таким способом, не всегда правильно отображаются в Excel.

    Сохраняем файл .xlsx как .xls и затем преобразуем в файл CSV

    Для этого способа не требуется каких-либо дополнительных комментариев, так как из названия уже всё ясно.

    Это решение я нашёл на одном из форумов, посвящённых Excel, уже не помню, на каком именно. Честно говоря, я никогда не использовал этот способ, но, по отзывам множества пользователей, некоторые специальные символы теряются, если сохранять непосредственно из .xlsx в .csv, но остаются, если сначала .xlsx сохранить как .xls, и затем как .csv, как мы делали в начале этой статьи.

    Так или иначе, попробуйте сами такой способ создания файлов CSV из Excel, и если получится, то это будет хорошая экономия времени.

    Сохраняем файл Excel как CSV при помощи OpenOffice

    OpenOffice – это пакет приложений с открытым исходным кодом, включает в себя приложение для работы с таблицами, которое отлично справляется с задачей экспорта данных из формата Excel в CSV. На самом деле, это приложение предоставляет доступ к большему числу параметров при преобразовании таблиц в файлы CSV (кодировка, разделители и так далее), чем Excel и Google Sheets вместе взятые.

    Просто открываем файл Excel в OpenOffice Calc, нажимаем Файл > Сохранить как (File > Save as) и выбираем тип файла Текст CSV (Text CSV).

    На следующем шаге предлагается выбрать значения параметров Кодировка (Character sets) и Разделитель поля (Field delimiter). Разумеется, если мы хотим создать файл CSV UTF-8 с запятыми в качестве разделителей, то выбираем UTF-8 и вписываем запятую (,) в соответствующих полях. Параметр Разделитель текста (Text delimiter) обычно оставляют без изменения – кавычки («). Далее нажимаем ОК.

    Преобразование Excel в CSV

    Таким же образом для быстрого и безболезненного преобразования из Excel в CSV можно использовать ещё одно приложение – LibreOffice. Согласитесь, было бы здорово, если бы Microsoft Excel предоставил возможность так же настраивать параметры при создании файлов CSV.

    В этой статье я рассказал об известных мне способах преобразования файлов Excel в CSV. Если Вам знакомы более эффективные методы экспорта из Excel в CSV, расскажите об этом в комментариях. Благодарю за внимание!

    Оцените качество статьи. Нам важно ваше мнение:

    Понравилась статья? Поделить с друзьями:
  • Text format in excel cell
  • Text date to date format in excel
  • Text form in word 2010
  • Text corrections in word
  • Text flashing in word