Programing

Excel 용 CSV 파일 생성, 값 내에 줄 바꿈이있는 방법

lottogame 2020. 6. 15. 08:19
반응형

Excel 용 CSV 파일 생성, 값 내에 줄 바꿈이있는 방법


Excel 용 파일을 생성 해야하는 데이 파일의 일부 값에 여러 줄이 포함되어 있습니다.

영어가 아닌 텍스트도 포함되어 있으므로 파일은 유니 코드 여야합니다.

내가 생성하는 파일은 이제 다음과 같습니다 (UTF8에서 영어가 아닌 텍스트가 혼합되어 많은 행이 있음)

Header1,Header2,Header3
Value1,Value2,"Value3 Line1
Value3 Line2"

여러 줄 값은 큰 따옴표로 묶고 보통 줄 바꿈 문자로 묶습니다.

내가 웹에서 발견 한 것으로 작동하지만 적어도 Excel 2007 및 UTF8 파일을 얻지는 못했지만 Excel은 세 번째 줄을 첫 번째 데이터 행의 두 번째 줄이 아닌 두 번째 데이터 행으로 처리합니다. .

이것은 고객의 컴퓨터에서 실행되어야하며 Excel 버전을 제어 할 수 없으므로 Excel 2000 이상에서 작동하는 솔루션이 필요합니다.

감사

편집 : 두 가지 CSV 옵션, Excel (유니 코드, 탭 구분, 필드에 줄 바꿈 없음) 및 나머지 세계 (UTF8, 표준 CSV)에 대한 두 가지 CSV 옵션을 사용하여 문제를 "해결했습니다".

내가 찾고있는 것이 아니라 적어도 작동합니다 (지금까지)


공백 문자가 데이터의 일부인 경우에만 필드 시작 부분에 공백 문자가 있어야합니다. Excel은 선행 공백을 제거하지 않습니다. 제목과 데이터 필드에 원하지 않는 공간이 생깁니다. 더 나쁜 것은 "세 번째 열의 줄 바꿈이 필드의 시작 부분이 아니기 때문에 무시되는 것입니다.

파일에 ASCII가 아닌 문자 (UTF-8로 인코딩 됨)가있는 경우 파일 hex EF BB BF시작 부분에 UTF-8 BOM (3 바이트 )이 있어야합니다. 그렇지 않으면 Excel은 utf-8 대신 로케일의 기본 인코딩 (예 : cp1252)에 따라 데이터를 해석하고 ASCII가 아닌 문자는 휴지통에 버립니다.

다음 의견은 Excel 2003, 2007 및 2013에 적용됩니다. Excel 2000에서 테스트되지 않음

Windows 탐색기에서 파일 이름을 두 번 클릭하여 파일을 열면 모든 것이 정상적으로 작동합니다.

Excel 내에서 열면 결과가 다릅니다.

  1. 파일에는 ASCII 문자 만 있고 BOM은 없습니다 : 작동합니다.
  2. 파일에 ASCII가 아닌 문자 (UTF-8로 인코딩 됨)가 UTF-8 BOM으로 시작됩니다. 데이터가 UTF-8로 인코딩되었음을 인식하지만 csv 확장자는 무시하고 텍스트 로 이동시킵니다. 불행히도 줄 바꿈 문제가 발생하여 not-a-Wizard 를 가져옵니다.

옵션은 다음과 같습니다.

  1. Excel 내에서 파일을 열지 않도록 사용자를 교육하십시오.
  2. XLS 파일을 직접 작성하는 것을 고려하십시오 .Python / Perl / PHP / .NET / etc에 패키지 / 라이브러리가 있습니다.

많은 조정을 거친 후 임베디드 줄 바꿈 형식이 표준을 따르지 않지만 Linux에서 파일을 생성하고 Windows + Excel에서 읽는 구성이 있습니다 .

  • 필드 내의 줄 바꿈은 \ n이어야합니다 (그리고 분명히 큰 따옴표로 인용).
  • 레코드 끝 : \ r \ n
  • 같음으로 필드를 시작하지 않아야합니다. 그렇지 않으면 수식으로 처리되고 잘립니다.

Perl에서는 Text :: CSV를 사용하여 다음과 같이했습니다.

use Text::CSV;

open my $FO, ">:encoding(utf8)", $filename or die "Cannot create $filename: $!";
my $csv = Text::CSV->new({ binary => 1, eol => "\r\n" });

#for each row...:
$csv -> print ($FO, \@row);

최근에 비슷한 문제가 있었고 HTML 파일 을 가져 와서 해결했습니다 . 기준 예는 다음과 같습니다.

<html xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
  <head>
    <style>
      <!--
      br {mso-data-placement:same-cell;}
      -->
    </style>
  </head>
  <body>
    <table>
      <tr>
        <td>first line<br/>second line</td>
        <td style="white-space:normal">first line<br/>second line</td>
      </tr>
    </table>
  </body>
</html>

CSV가 아니며 다양한 버전의 Excel에서 다르게 작동 할 수도 있지만 시도해 볼 가치가 있다고 생각합니다.

이게 도움이 되길 바란다 ;-)


.CSV 파일에 줄 바꿈이 포함 된 큰 따옴표로 묶은 필드가있는 경우 .CSV 파일이 UTF-8 형식으로 작성된 경우 Excel에서 .CSV 파일을 올바르게 가져 오지 않습니다. Excel은 줄 바꿈을 마치 CR / LF 인 것처럼 취급하고 새 줄을 시작합니다. 스프레드 시트가 깨졌습니다. 세미콜론이 쉼표 대신 필드 구분 기호로 사용되는 경우에도 마찬가지입니다.

The problem can be resolved by using Windows Notepad to edit the .CSV file, using File > Save As... to save the file, and before saving the file, changing the file encoding from UTF-8 to ANSI. Once the file is saved in ANSI format, then I find that Microsoft Excel 2013 running on Windows 7 Professional will import the file properly.


Newline inside a value seems to work if you use semicolon as separator, instead of comma or tab, and use quotes.

This works for me in both Excel 2010 and Excel 2000. However, surprisingly, it works only when you open the file as a new spreadsheet, not when you import it into an existing spreadsheet using the data import feature.


On a PC, ASCII character #10 is what you want to place a newline within a value.

Once you get it into Excel, however, you need to make sure word wrap is turned on for the multi-line cells or the newline will appear as a square box.


This will not work if you try to import the file into EXCEL.

Associate the file extension csv with EXCEL.EXE so you will be able to invoke EXCEL by double-clicking the csv file.

Here I place some text followed by the NewLine Char followed by some more text AND enclosing the whole string with double quotes.

Do not use a CR since EXCEL will place part of the string in the next cell.

""text" + NL + "text""

When you invoke EXCEL, you will see this. You may have to auto size the height to see it all. Where the line breaks will depend on the width of the cell.

2

DATE

Here's the code in Basic

CHR$(34,"2", 10,"DATE", 34)

I found this and it has worked for me

$delimiter = ',';
$enc1 = '"';
$enc2 = '""';

Then where you need to have stuff enclosed

$myfile = ('/path/to/myfile.csv');
//erase any previous contents
$fp = fopen($myfile, 'w+');
fwrite($fp, $enc1 .  'Column Heading 1' . $enc1 . $delimiter );
//append to new file
$fp2 = fopen($myfile, 'a');
fwrite($fp2, $enc1 .  'Column Heading 2' . $enc1 . $delimiter );

.....

fwrite($fp2, $enc1 .  'Last Column Heading' . $enc1 . $delimiter. PHP_EOL );

Then when you need to write something out - like HTML that includes the " you can do this

fwrite($fp2, $enc2 .  $myhtmlstring . $enc2 . $delimiter);

New lines end with . PHP_EOL

The end of the script prints out a link so that the user can download the file.

echo 'Click <a href="myfile.csv">here</a> to download file';

UTF files that contain a BOM will cause Excel to treat new lines literally even in that field is surrounded by quotes. (Tested Excel 2008 Mac)

The solution is to make any new lines a carriage return (CHR 13) rather than a line feed.


Test this: It fully works for me: Put the following lines in a xxxx.csv file

hola_x,="este es mi text1"&CHAR(10)&"I sigo escribiendo",hola_a

hola_y,="este es mi text2"&CHAR(10)&"I sigo escribiendo",hola_b

hola_z,="este es mi text3"&CHAR(10)&"I sigo escribiendo",hola_c

Open with excel.

in some cases will open directly otherwise will need to use column to data conversion. expand the column width and hit the wrap text button. or format cells and activate wrap text.

and thanks for the other suggestions, but they did not work for me. I am in a pure windows env, and did not want to play with unicode or other funny thing.

This way you putting a formula from csv to excel. It may be many uses for this method of work. (note the = before the quotes)

pd:In your suggestions please put some samples of the data not only the code.


putting "\r" at the end of each row actually had the effect of line breaks in excel, but in the .csv it vanished and left an ugly mess where each row was squashed against the next with no space and no line-breaks


The way we do it (we use VB.Net) is to enclose the text with new lines in Chr(34) which is the char representing the double quotes and replace all CR-LF characters for LF.


Normally a new line is "\r\n". In my CSV, I replaced "\r" with empty value. Here is code in Javascript:

cellValue = cellValue.replace(/\r/g, "")

When I open the CSV in MS Excel, it worked well. If a value has multiple lines, it will stay within 1 single cell in the Excel sheet.


For File Open only, the syntax is

 ,"one\n
 two",...

The critical thing is that there is no space after the first ",". Normally spaces are fine, and trimmed if the string is not quoted. But otherwise nasty. Took me a while to figure that out.

It does not seem to matter if the line is ended \n or \c\n.

Make sure you expand the formula bar so you can actually see the text in the cell (got me after a long day...)

Now of course, File Open will not support UTF-8 Properly (unless one uses tricks).

Excel > Data > Get External Data > From Text

Can be set into UTF-8 mode (it is way down the list of fonts). However, in that case the new lines do not seem to work and I know no way to fix that.

(One might thing that after 30 years MS would get this stuff right.)


In Excel 365 while importing the file:

Data -> From Text/CSV -> Select File > Transform Data -> Data Source Configuration -> Select Data Source -> Click Edit Source -> In the line break dropdown select Ignore line breaks inside quotes.

The above text was translated from Portuguese so the wording might be different in English.


you can do the next "\"Value3 Line1 Value3 Line2\"". It works for me generating a csv file in java


Here is an interesting approach using JavaScript ...

  String.prototype.csv = String.prototype.split.partial(/,\s*/);  

  var results = ("Mugan, Jin, Fuu").csv();                        

  console.log(results[0]=="Mugan" &&                                   
         results[1]=="Jin" &&                                     
         results[2]=="Fuu",                                       
         "The text values were split properly");                  

Printing a HTML newline <br/> into the content and opening in excel will work fine on any excel


You could use keyboard shortcut ALT+Enter.

  1. Select the cell you wish to edit
  2. enter edit mode either by double clicking it or pressing F2 3.Press Alt+enter. This will create a new line in cell

참고URL : https://stackoverflow.com/questions/1241220/generating-csv-file-for-excel-how-to-have-a-newline-inside-a-value

반응형