program story

Excel 2007에서 줄 바꿈이있는 CSV 가져 오기

inputbox 2020. 8. 12. 08:15
반응형

Excel 2007에서 줄 바꿈이있는 CSV 가져 오기


검색 결과를 Excel에서 열 수있는 CSV 파일로 내보내는 기능을 개발 중입니다. 필드 중 하나는 줄 바꿈, 쉼표, 따옴표 등을 포함 할 수있는 자유 텍스트 필드입니다.이 문제를 해결하기 위해 필드를 큰 따옴표 ( ")로 묶었습니다.

그러나 데이터를 Excel 2007로 가져오고 적절한 구분 기호를 설정하고 텍스트 한정자를 큰 따옴표로 설정하면 줄 바꿈이 여전히 줄 바꿈에서 새 레코드를 생성합니다. 여기서 전체 텍스트 필드를 단세포.

또한 CR / LF (\ r \ n)를 CR (\ r)로 바꾸고 다시 LF (\ n)로 바꾸려고 시도했지만 운이 없습니다.

다른 사람이이 동작을 경험 한 적이 있습니까? 그렇다면 어떻게 해결 했습니까?

TIA,
-J

편집 :
여기에 문제를 복제하기 위해 손으로 쓴 빠른 파일이 있습니다.

아이디, 이름, 설명
"12345", "Smith, Joe", "Hey.
My name is Joe."

이것을 Excel 2007로 가져 오면 헤더 행과 두 개의 레코드가 생깁니다. "Smith, Joe"의 쉼표는 제대로 처리되고 있습니다. 문제를 일으키는 것은 줄 바꿈뿐입니다.


Excel (최소한 XP의 Office 2007에서)은 CSV 파일을 파일-> 열기 메뉴에서 열거 나 탐색기에서 파일을 두 번 클릭하여 가져 오는지 여부에 따라 다르게 작동 할 수 있습니다.

UTF-8 인코딩이고 일부 셀에 줄 바꿈이 포함 된 CSV 파일이 있습니다. Excel의 파일-> 열기 메뉴에서이 파일을 열면 "CSV 가져 오기"마법사가 나타나고 파일을 올바르게 가져올 수 없습니다. 줄 바꿈은 따옴표로 묶여도 새 행을 시작합니다. 탐색기 창에서이 파일을 두 번 클릭하여 열면 마법사의 개입없이 올바르게 열립니다.


제안 된 솔루션 중 어느 것도 나를 위해 일하지 않았습니다.

실제로 작동하는 것 (모든 인코딩 사용) :

csv 파일 (Editor에서 열기)에서 데이터를 복사 / 붙여 넣기 한 다음 "text in columns"수행-> 작동하지 않습니다.

다음 탭으로 이동하여 다시 복사 / 붙여 넣기 (클립 보드에 이미있는 것과 동일)-> 이제 자동으로 작동합니다.


마침내 문제를 발견했습니다!

ASCII 또는 UTF-8이 아닌 유니 코드 인코딩을 사용하여 파일을 작성하는 것으로 나타났습니다. FileStream에서 인코딩을 변경하면 문제가 해결되는 것 같습니다.

모든 제안에 감사드립니다!


이 작업을 수동으로 수행하는 경우 LibreOffice를 다운로드하고 LibreOffice Calc를 사용하여 CSV를 가져옵니다. 내가 시도한 Excel 버전보다 이와 같은 작업을 훨씬 더 잘 수행하며 나중에 Excel로 전송해야하는 경우 필요에 따라 XLS 또는 XLSX에 저장할 수 있습니다.

그러나 Excel을 사용하고 있고 더 나은 수정이 필요한 경우 방법이있는 것 같습니다. 로케일 의존적 인 것 같습니다 (내 겸손한 의견으로는 어리석은 것처럼 보입니다). Excel 2007은 없지만 Excel 2010이 있고 예제는 다음과 같습니다.

ID,Name,Description
"12345","Smith, Joe","Hey.
My name is Joe."

작동하지 않습니다. 메모장에서 작성하고 다른 이름으로 저장 ...을 선택했으며 저장 버튼 옆에서 인코딩을 선택할 수 있습니다. 제안대로 UTF-8을 선택했지만 운이 없었습니다. 그래도 쉼표를 세미콜론으로 변경하면 효과가있었습니다. 나는 다른 것을 변경하지 않았고 단지 효과가있었습니다. 그래서 예제를 다음과 같이 변경하고 메모장에 저장할 때 UTF-8 인코딩을 선택했습니다.

ID;Name;Description
"12345";"Smith, Joe";"Hey.
My name is Joe."

하지만 문제가 있습니다! 작동하는 유일한 방법은 CSV 파일을 두 번 클릭하여 Excel에서 여는 것입니다. 텍스트에서 데이터를 가져오고이 CSV를 선택하면 인용 된 줄 바꿈에서 여전히 실패합니다.

하지만 또 다른 문제가 있습니다 ! 작업 필드 구분 기호 (원래 예에서는 쉼표, 필자의 경우 세미콜론)는 시스템의 지역 설정 (제어판-> 지역 및 언어에서 설정)에 따라 달라지는 것 같습니다. 노르웨이에서는 쉼표가 소수점 구분 기호입니다. Excel은이 문자를 피하고 대신 세미콜론을 선호합니다. 영국 영어 로케일로 설정된 다른 컴퓨터에 액세스 할 수 있으며 해당 컴퓨터에서 쉼표 구분 기호가있는 첫 번째 예가 제대로 작동하고 (더블 클릭시에만) 세미콜론이있는 컴퓨터는 실제로 실패합니다! 상호 운용성을 위해 너무 많이. 이 CSV를 온라인으로 게시하고 사용자가 Excel을 사용하는 경우 두 버전을 모두 게시해야하며 사람들이 올바른 행 수를 제공하는 파일을 확인하는 것이 좋습니다.

이 작업을 수행하기 위해 수집 한 모든 세부 정보는 다음과 같습니다.

  1. The file must be saved as UTF-8 with a BOM, which is what Notepad does when you chose UTF-8. I tried UTF-8 without BOM (can be switched easily in Notepad++), but then double-clicking the document fails.
  2. You must use a comma or a semicolon separator, but not the one that is the decimal separator in your Regional Settings. Perhaps other characters work, but I don't know which.
  3. You must quote fields that contain a newline with the " character.
  4. I've used Windows line-endings (\r\n) both in the text field and as a record separator, that works.
  5. You must double-click the file to open it, importing data from text doesn't work.

Hope this helps someone.


Short Answer

Remove the newline/linefeed characters (\n with Notepad++). Excel will still recognise the carriage return character (\r) to separate records.

Long Answer

As mentioned newline characters are supported inside CSV fields but Excel doesn't always handle them gracefully. I faced a similar issue with a third party CSV that possibly had encoding issues but didn't improve with encoding changes.

What worked for me was removing all newline characters (\n). This has the effect of collapsing fields to a single record assuming that your records are separated by the combination of a carriage return and a newline (CR/LF). Excel will then properly import the file and recognise new records by the carriage return.

Obviously a cleaner solution is to first replace the real newlines (\r\n) with a temporary character combination, replacing the newlines (\n) with your seperating character of choice (e.g. comma in a semicolon file) and then replacing the temporary characters with proper newlines again.


If the field contains a leading space, Excel ignores the double quote as a text qualifier. The solution is to eliminate leading spaces between the comma (field separator) and double-quote. For example:

Broken:
Name,Title,Description
"John", "Mr.", "My detailed description"

Working:
Name,Title,Description
"John","Mr.","My detailed description"


+1 on J Ashley's comment. I ran into this problem also. It turns out that Excel requires:

  • A newline character("\n") in the quoted string

  • A carriage return and newline between each row.

E.g. "Test", "Multiline item\n multiline item"\r\n "Test2", "Multiline item\n multiline item"\r\n

I used notepad ++ to delimit each row properly and to only use newlines in the string. Discovered this by creating multiline entries in a blank excel doc and opening the csv in notepad ++.


Paste into Notepad++, select Encoding > Encode in ANSI, copy all again and paste into Excel :)


If anyone stumbling across this thread and is looking for a definitive answer here goes (credit to the person mentioning LibreOffice:

1) Install LibreOffice 2) Open Calc and import file 3) My txt file had the fields separated by , and character fields enclosed in " 4) save as ODS file 5) Open ODS file in Excel 6) Save as .xls(x) 7) Done. 8) This worked perfectly for me and saved me BIGTIME!


My experience with Excel 2010 on WinXP with French regional settings

  • the separator of your imported csv must correspond to the list separator of your regional settings (; in my case)
  • you must double click on the file from the explorer. don't open it from Excel

I had a similar problem. I had some twitter data in MySQL. The data had Line feed( LF or \n) with in the data. I had a requirement of exporting the MySQL data into excel. The LF was messing up my import of csv file. So I did the following -

1. From MySQL exported to CSV with Record separator as CRLF
2. Opened the data in notepad++ 
3. Replaced CRLF (\r\n) with some string I am not expecting in the Data. I used ###~###! as replacement of CRLF
4. Replaced LF (\n) with Space
5. Replaced ###~###! with \r\n, so my record separator are back.
6. Saved and then imported into Excel

NOTE- While replacing CRLF or LF dont forget to Check Excended (\n,\r,\t... Checkbox [look at the left hand bottom of the Dialog Box)


Use Google Sheets and import the CSV file.

Then you can export that to use in Excel


What just worked for me, importing into Excel directly provided that the import is done as a text format instead as csv format. M/


just create a new sheet with cells with linebreak, save it to csv then open it with an editor that can show the end of line characters (like notepad++). By doing that you will notice that a linebreak in a cell is coded with LF while a "real" end of line is code with CR LF. Voilà, now you know how to generate a "correct" csv file for excel.


I also had this problem: ie., csv files (comma delimited, double quote delimited strings) with LF in quoted strings. These were downloaded Square files. I did a data import but instead of importing as text files, imported as "from HTML". This time it ignored the LF's in the quoted strings.


This worked on Mac, using csv and opening the file in Excel.

Using python to write the csv file.

data= '"first line of cell a1\r 2nd line in cell a1\r 3rd line in cell a1","cell b1","1st line in cell c1\r 2nd line in cell c1"\n"first line in cell a2"\n'

file.write(data)


On MacOS try using Numbers

If you have access to Mac OS I have found that the Apple spreadsheet Numbers does a good job of unpicking a complex multi-line CSV file that Excel could not handle. Just open the .csv with Numbers and then export to Excel.


In my case opening CSV in notepad++ and adding SEP="," as the first line allows me open CSV with line breaks and utf-8 in Excel without issues


Replace the separator with TAB(\t) instead of comma(,). Then open the file in your editor (Notepad etc.), copy the content from there, then paste it in the Excel file.


Line breaks inside double quotes are perfectly fine according to CSV standard. The parsing of line breaks in Excel depends on the OS setting of list separator:

  1. Windows: you need to set the list seperator to comma (Region and language » Formats » Advanced) Source: https://superuser.com/questions/238944/how-to-force-excel-to-open-csv-files-with-data-arranged-in-columns#answer-633302

  2. Mac: Need to change the region to US (then to manually change back other settings to your preference) Source: https://answers.microsoft.com/en-us/mac/forum/macoffice2016-macexcel/line-separator-comma-semicolon-in-excel-2016-for/7db1b1a0-0300-44ba-ab9b-35d1c40159c6 (see NewmanLee's answer)

Don't forget to close Excel completely before trying again.

I've succesfully replicated the issue and was able to fix it using the above in both Max and Windows.


Excel is incredibly broken when dealing with CSVs. LibreOffice does a much better job. So, I found out that:

  • The file must be encoded in UTF-8 with BOM, so consider this for all the points below
  • The best result, by far, is achieved by opening it from File Explorer
  • If you open it from within Excel there are two possible outcomes:
    • If it has only ASCII characters, it will most likely work
    • If it has non-ASCII characters, it will mess your line breaks
  • It seems to be heavily dependent on the decimal separator configured in the OS's regional settings, so you have to select the right one
  • I would bet that it may also behave differently depending on OS and Office version

참고URL : https://stackoverflow.com/questions/2668678/importing-csv-with-line-breaks-in-excel-2007

반응형