Excel to csv with separator

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.

I don’t see an option immediately in Excel, but I can offer some advice.

Remember that CSV files are Comma Separated Values, which follows a standard: Data, a comma, data, a comma, etc. To break this means it will not follow the specification.

What happens if you have a comma in your data though? Excel will automatically surround that cell’s content with quotation marks ("), so the program importing the file will know when that cell actually ends.

If you do not want a comma as a separator, you can save the file as a CSV still, then edit it manually. Open a text editor like Notepad or Notepad++. Do a search for whatever character you want to use (i.e. in Notepad, go to Edit->Find). If you want a pipe, search for a pipe (|). If you hit any results, do not use this character. To search for a tab easily, I’d recommend using Notepad++.

Once you find that the character you want to use isn’t being used elsewhere in your document, then you can do a Search and Replace. In Notepad, go to Edit->Replace…. In ‘Find what:’, type a comma. In ‘Replace with:’, type the character you want to use for the separator. The next part is to hit Find Next. The reason for this, is that if there are commas in your data as well, this will break your file. Only replace the commas that are delimiters of the data, and nothing in quotation marks.

Once this is done, you can save the file. If you want to import it, I’d recommend renaming it to a .TXT file, so Excel will ask you what the Field Delimiter Character is. If you choose to open a .CSV file, it will automatically use a comma as the delimiter, which is what you don’t want.

How is a CSV file built in general? With commas or semicolons?
Any advice on which one to use?

Lance Roberts's user avatar

Lance Roberts

22.2k32 gold badges112 silver badges129 bronze badges

asked Apr 13, 2012 at 12:39

membersound's user avatar

membersoundmembersound

79.5k182 gold badges566 silver badges1081 bronze badges

3

In Windows it is dependent on the «Regional and Language Options» customize screen where you find a List separator. This is the char Windows applications expect to be the CSV separator.

Of course this only has effect in Windows applications, for example Excel will not automatically split data into columns if the file is not using the above mentioned separator. All applications that use Windows regional settings will have this behavior.

If you are writing a program for Windows that will require importing the CSV in other applications and you know that the list separator set for your target machines is ,, then go for it, otherwise I prefer ; since it causes less problems with decimal points, digit grouping and does not appear in much text.

Marcos Dimitrio's user avatar

answered Apr 13, 2012 at 12:49

Sibster's user avatar

5

CSV is a standard format, outlined in RFC 4180 (in 2005), so there IS no lack of a standard. https://www.ietf.org/rfc/rfc4180.txt

And even before that, the C in CSV has always stood for Comma, not for semiColon :(

It’s a pity Microsoft keeps ignoring that and is still sticking to the monstrosity they turned it into decades ago (yes, I admit, that was before the RFC was created).

  • One record per line, unless a newline occurs within quoted text (see below).
  • COMMA as column separator. Never a semicolon.
  • PERIOD as decimal point in numbers. Never a comma.
  • Text containing commas, periods and/or newlines enclosed in «double quotation marks».
  • Only if text is enclosed in double quotation marks, such quotations marks in the text escaped by doubling. These examples represent the same three fields:

    1,»this text contains «»quotation marks»»»,3

    1,this text contains «quotation marks»,3

The standard does not cover date and time values, personally I try to stick to ISO 8601 format to avoid day/month/year — month/day/year confusion.

answered Jun 18, 2015 at 14:45

Luc VdV's user avatar

Luc VdVLuc VdV

1,0189 silver badges13 bronze badges

11

I’d say stick to comma as it’s widely recognized and understood. Be sure to quote your values and escape your quotes though.

ID,NAME,AGE
"23434","Norris, Chuck","24"
"34343","Bond, James ""master""","57"

answered Apr 13, 2012 at 12:41

adarshr's user avatar

adarshradarshr

60.9k23 gold badges137 silver badges167 bronze badges

4

Also relevant, but specially to excel, look at this answer and this other one that suggests, inserting a line at the beginning of the CSV with

"sep=,"

To inform excel which separator to expect

answered Nov 21, 2016 at 12:23

Rafareino's user avatar

RafareinoRafareino

2,4251 gold badge19 silver badges26 bronze badges

1

1.> Change File format to .CSV (semicolon delimited)

To achieve the desired result we need to temporary change the delimiter setting in the Excel Options:

Move to File -> Options -> Advanced -> Editing Section

Uncheck the “Use system separators” setting and put a comma in the “Decimal Separator” field.

Now save the file in the .CSV format and it will be saved in the semicolon delimited format.

Anil_M's user avatar

Anil_M

10.7k6 gold badges45 silver badges72 bronze badges

answered Aug 9, 2016 at 13:47

hugo bourret-desmarais's user avatar

CSV is a Comma Seperated File. Generally the delimiter is a comma, but I have seen many other characters used as delimiters. They are just not as frequently used.

As for advising you on what to use, we need to know your application. Is the file specific to your application/program, or does this need to work with other programs?

answered Apr 13, 2012 at 12:40

Youssef G.'s user avatar

Youssef G.Youssef G.

6074 silver badges10 bronze badges

3

To change comma to semicolon as the default Excel separator for CSV — go to Region -> Additional Settings -> Numbers tab -> List separator
and type ; instead of the default ,

answered Feb 15, 2016 at 7:50

Michael's user avatar

1

Well to just to have some saying about semicolon. In lot of country, comma is what use for decimal not period. Mostly EU colonies, which consist of half of the world, another half follow UK standard (how the hell UK so big O_O) so in turn make using comma for database that include number create much of the headache because Excel refuse to recognize it as delimiter.

Like wise in my country, Viet Nam, follow France’s standard, our partner HongKong use UK standard so comma make CSV unusable, and we use t or ; instead for international use, but it still not «standard» per the document of CSV.

answered Nov 16, 2016 at 8:17

Tran Vu Dang Khoa's user avatar

best way will be to save it in a text file with csv extension:

Sub ExportToCSV()
Dim i, j As Integer
Dim Name  As String

Dim pathfile As String

Dim fs As Object
    Dim stream As Object

    Set fs = CreateObject("Scripting.FileSystemObject")
On Error GoTo fileexists

i = 15
Name = Format(Now(), "ddmmyyHHmmss")
pathfile = "D:1" & Name & ".csv"

Set stream = fs.CreateTextFile(pathfile, False, True)

fileexists:

If Err.Number = 58 Then
    MsgBox "File already Exists"
    'Your code here
    Return
End If
On Error GoTo 0

j = 1
Do Until IsEmpty(ThisWorkbook.ActiveSheet.Cells(i, 1).Value)

    stream.WriteLine (ThisWorkbook.Worksheets(1).Cells(i, 1).Value & ";" & Replace(ThisWorkbook.Worksheets(1).Cells(i, 6).Value, ".", ","))

    j = j + 1
    i = i + 1
Loop


stream.Close

End Sub

hering's user avatar

hering

1,9464 gold badges28 silver badges43 bronze badges

answered Jul 31, 2017 at 6:28

AzizD's user avatar

AzizDAzizD

10310 bronze badges

Short Trick
In default if converting Excel (.xls or .xlsx)  to CSV the result is comma delimited. This is because setting list separator in your control panel.

If we want to convert excel to csv with semicolon delimited, the easy way is the changing list separator in control panel.
1. Control Panel
2. Region, Region and Language Option
3. In Tab Format, click customize this format
4. List separator, change from comma (,) to semicolon (;)
5. Ok, -Finish-

And we can try again convert to CSV the result is semicolon delimited.

CSV стенды для значения через запятую, что означает текстовый файл, в котором для разделения значений используется запятая. Но файл CSV также может использовать символ точки с запятой в качестве разделителя списка. Иногда файл с разделителями-запятыми — это не то, что вам нужно, вместо этого вам нужен файл, разделенный точкой с запятой. В этом уроке мы поговорим о том, как изменить разделитель файлов при экспорте файла Excel в формате CSV.
документ изменить-разделитель-при-сохранении-как-csv 1

Изменить разделитель при сохранении файла Excel в формате CSV


изменить разделитель при сохранении файла Excel в формате CSV

В таких странах, как США и UK, разделитель списка по умолчанию — это запятая, поэтому файл CSV разделен запятыми. В то время как во многих европейские страны, точка с запятой используется в качестве разделителя списка по умолчанию, поскольку запятая установлена ​​в качестве десятичного символа. Это означает, что в Европе файл CSV обычно разделяется точкой с запятой. Чтобы изменить разделитель при сохранении файла Excel в формате CSV, сделайте следующее.

Обратите внимание, что в нашем примере разделителем списка по умолчанию является запятая.

1. Откройте Эксель. Чтобы изменить разделитель списка с запятой на точку с запятой, щелкните Файл > Опции, Параметры Excel всплывает диалоговое окно. Нажмите на Дополнительно опцию.
документ изменить-разделитель-при-сохранении-как-csv 2

2. в Параметры редактирования раздел, снимите флажок что собой представляет Используйте системные разделители пунктом.
документ изменить-разделитель-при-сохранении-как-csv 3

3. Установить Десятичный разделитель в запятая (,) и установите Тысяча сепараторов в период (.). Нажмите OK.
документ изменить-разделитель-при-сохранении-как-csv 4

4. Откройте файл Excel, который вы хотите сохранить в формате CSV. Нажмите Файл > Сохранить как.

5. Сохранить как всплывает диалоговое окно. Измените тип Сохранить как на CSV (с разделителями-запятыми) в раскрывающемся списке.
документ изменить-разделитель-при-сохранении-как-csv 5

6. Откройте файл CSV, который вы только что сохранили, с помощью Блокнота. Вы увидите, что этот файл CSV точка с запятой.
документ изменить-разделитель-при-сохранении-как-csv 6

Заметки

  1. Если ты хочешь изменить разделитель списка обратно в запятая, Вы можете проверка что собой представляет Используйте системные разделители коробка. Или установите Десятичный разделитель в период (.) и установите Тысяча сепараторов в запятая (,).
    документ изменить-разделитель-при-сохранении-как-csv 7
  2. In европейские страны, чтобы изменить разделитель с точка с запятой в запятая, вы также должны снимите флажок что собой представляет Используйте системные разделители коробка. Затем установите Десятичный разделитель в период (.) и установите Тысяча сепараторов в запятая (,).

Прочие операции (статьи)

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

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

Как разделить текст по пробелу/запятой/разделителю в Excel?
Если у вас есть список столбцов с данными, и вы хотите разделить их на несколько столбцов с помощью определенного разделителя, как на приведенных ниже снимках экрана, как вы можете разделить их в Excel? Возможно, некоторые из пользователей думают только о функции Text to Column, но теперь я представлю вам не только функцию Text to Columns, но и код VBA.


Лучшие инструменты для работы в офисе

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы и хранение данных; Разделить содержимое ячеек; Объедините повторяющиеся строки и сумму / среднее значение… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Избранные и быстро вставляйте формулы, Диапазоны, диаграммы и изображения; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Группировка сводной таблицы по номер недели, день недели и другое … Показать разблокированные, заблокированные ячейки разными цветами; Выделите ячейки, у которых есть формула / имя

вкладка kte 201905


Вкладка Office — предоставляет интерфейс с вкладками в Office и значительно упрощает вашу работу

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

Комментарии (0)


Оценок пока нет. Оцените первым!

Понравилась статья? Поделить с друзьями:
  • Excel to csv with delimiter
  • Excel to csv windows
  • Excel to csv npm
  • Excel to csv linux
  • Excel to count occurrences