Programming

Microsoft Excel에서 .csv 파일의 분음 부호를 표시합니까?

procodes 2020. 5. 16. 11:25
반응형

Microsoft Excel에서 .csv 파일의 분음 부호를 표시합니까?


프로그래밍 방식으로 데이터를 PHP 5.2를 사용하여 .csv 테스트 파일로 내보내고 있습니다.
데이터 예 : Numéro 1(강조 e를 참고하십시오). 데이터는 utf-8(선두 BOM이 없음)입니다.

이 파일을 MS Excel에서 열면이 표시됩니다 Numéro 1.

텍스트 편집기 (UltraEdit)에서 올바르게 열 수 있습니다. UE는 캐릭터가보고합니다 decimal 233.

가져 오기 마법사 또는 기본이 아닌 마법사 설정을 사용하지 않고 MS Excel 에서 텍스트 데이터를 올바르게 렌더링 하도록 텍스트 데이터를 .csv 파일로 내보내 려면 어떻게 해야합니까?


올바른 형식의 UTF8 파일은 바이트 순서 표시 를 처음 세 옥텟으로 가질 수 있습니다 . 16 진수 값 0xEF, 0xBB, 0xBF입니다. 이 8 진수는 파일을 UTF8로 표시하는 역할을합니다 ( "바이트 순서"정보와 관련이 없기 때문에). 1 이 BOM이 존재하지 않으면 소비자 / 리더는 텍스트의 인코딩 유형을 유추해야합니다. UTF8을 지원하지 않는 리더는 바이트를 Windows-1252와 같은 다른 인코딩으로 읽고 파일 시작 부분에 문자 표시 합니다.

파일 연결을 통해 UTF8 CSV 파일을 열 때 Excel 에서 UTF8 BOM의 존재를 무시 하고 1 바이트 인코딩으로 가정하는 것으로 알려진 버그가 있습니다. 시스템 기본 코드 페이지 또는 언어 설정으로 이를 수정할 수 없습니다 . BOM은 Excel에서 단서가 아니며 작동하지 않습니다. 소수 보고서는 BOM이 때때로 "텍스트 가져 오기"마법사를 트리거한다고 주장합니다.이 버그는 Excel 2003 및 이전 버전에 존재하는 것으로 보입니다. 대부분의 보고서 (여기서 답변 중 가장 작음)는 이것이 Excel 2007 이상에서 수정되었다고 말합니다.

참고 당신 항상 *이 파일 당신에게있는 거 개방의 인코딩을 지정할 수 있습니다 "텍스트 가져 오기"마법사를 사용하여 Excel에서 제대로 열리지 UTF8의 CSV 파일. 물론 이것은 훨씬 덜 편리합니다.

이 답변을 읽는 독자는 특히 Excel <2007을 지원하지 않지만 원시 UTF8 텍스트를 Excel로 전송하여 텍스트를 잘못 해석하고 텍스트를 Ã유사한 Windows-1252 문자로 뿌려주 는 상황에 처할 가능성이 큽니다 . UTF8 BOM을 추가하는 것이 아마도 가장 빠르고 가장 좋은 해결책 일 것입니다.

이전 Excel의 사용자에게 붙어 있고 Excel이 CSV의 유일한 소비자 인 경우 UTF8 대신 UTF16을 내보내이 문제를 해결할 수 있습니다. Excel 2000 및 2003은이를 두 번 클릭하여 올바르게 엽니 다. (일부 다른 텍스트 편집기에는 UTF16에 문제가있을 수 있으므로 옵션을 신중하게 평가해야 할 수도 있습니다.)


* 할 수없는 경우를 제외하고 (적어도) Mac 가져 오기 마법 사용 Excel 2011은 사용자가 말한 내용에 관계없이 실제로 모든 인코딩에서 작동하지는 않습니다. </ anecdotal-evidence> :)


Excel에서 파일을 UTF-8로 인식했기 때문에 BOM 앞에 추가 (\ uFEFF) (Excel 2007)되었습니다. 그렇지 않으면 저장하고 가져 오기 마법사를 사용하는 것이 좋지만 덜 이상적입니다.


다음은 Microsoft Excel을 사용자에게 보낼 때 프로젝트에서 사용하는 PHP 코드입니다.

  /**
   * Export an array as downladable Excel CSV
   * @param array   $header
   * @param array   $data
   * @param string  $filename
   */
  function toCSV($header, $data, $filename) {
    $sep  = "\t";
    $eol  = "\n";
    $csv  =  count($header) ? '"'. implode('"'.$sep.'"', $header).'"'.$eol : '';
    foreach($data as $line) {
      $csv .= '"'. implode('"'.$sep.'"', $line).'"'.$eol;
    }
    $encoded_csv = mb_convert_encoding($csv, 'UTF-16LE', 'UTF-8');
    header('Content-Description: File Transfer');
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment; filename="'.$filename.'.csv"');
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: '. strlen($encoded_csv));
    echo chr(255) . chr(254) . $encoded_csv;
    exit;
  }

업데이트 : 파일 이름 개선 및 BUG 수정 올바른 길이 계산. TRiG@ ivanhoe011 에게 감사합니다


Excel 버전 (2003 + 2007)과 파일 형식의 모든 조합에 대한 답변

여기에있는 대부분의 다른 답변은 Excel 버전에만 해당되며 반드시 Excel 버전에만 해당되는 답변이 아니기 때문에 반드시 도움이되는 것은 아닙니다.

예를 들어 BOM 문자를 추가하면 자동 열 구분 기호 인식에는 문제가 있지만 모든 Excel 버전에는 해당되지 않습니다.

대부분의 Excel 버전에서 작동하는지 확인하는 3 가지 변수가 있습니다.

  • 부호화
  • BOM 캐릭터 존재
  • 세포 분리기

SAP를 훔친 사람이 모든 조합을 시도하고 결과를보고했습니다. 최종 결과? BOM 및 탭 문자와 함께 UTF16le을 구분 기호로 사용하여 대부분의 Excel 버전에서 작동합니다.

당신은 나를 믿지 않습니까? 나도 아니고 여기를 읽고 울다 : http://wiki.sdn.sap.com/wiki/display/ABAP/CSV+tests+of+encoding+and+column+separator


가져올 때 UTF-8 인코딩을 선택하십시오. Office 2007을 사용하는 경우 파일을 연 직후에 선택한 위치입니다.


CSV 데이터를 출력하기 전에 에코 UTF-8 BOM. 이것은 Windows의 모든 문자 문제를 해결하지만 Mac에서는 작동하지 않습니다.

echo "\xEF\xBB\xBF";

Windows PC에서만 사용되는 파일을 생성해야하기 때문에 저에게 효과적입니다.


UTF-8 doesn't work for me in office 2007 without any service pack, with or without BOM (U+ffef or 0xEF,0xBB,0xBF , neither works) installing sp3 makes UTF-8 work when 0xEF,0xBB,0xBF BOM is prepended.

UTF-16 works when encoding in python using "utf-16-le" with a 0xff 0xef BOM prepended, and using tab as seperator. I had to manually write out the BOM, and then use "utf-16-le" rather then "utf-16", otherwise each encode() prepended the BOM to every row written out which appeared as garbage on the first column of the second line and after.

can't tell whether UTF-16 would work without any sp installed, since I can't go back now. sigh

This is on windows, dunno about office for MAC.

for both working cases, the import works when launching a download directly from the browser and the text import wizard doesn't intervence, it works like you would expect.


As Fregal said \uFEFF is the way to go.

<%@LANGUAGE="JAVASCRIPT" CODEPAGE="65001"%>
<%
Response.Clear();
Response.ContentType = "text/csv";
Response.Charset = "utf-8";
Response.AddHeader("Content-Disposition", "attachment; filename=excelTest.csv");
Response.Write("\uFEFF");
// csv text here
%>

I've also noticed that the question was "answered" some time ago but I don't understand the stories that say you can't open a utf8-encoded csv file successfully in Excel without using the text wizard.

My reproducible experience: Type Old MacDonald had a farm,ÈÌÉÍØ into Notepad, hit Enter, then Save As (using the UTF-8 option).

Using Python to show what's actually in there:

>>> open('oldmac.csv', 'rb').read()
'\xef\xbb\xbfOld MacDonald had a farm,\xc3\x88\xc3\x8c\xc3\x89\xc3\x8d\xc3\x98\r\n'
>>> ^Z

Good. Notepad has put a BOM at the front.

Now go into Windows Explorer, double click on the file name, or right click and use "Open with ...", and up pops Excel (2003) with display as expected.


You can save an html file with the extension 'xls' and accents will work (pre 2007 at least).

Example: save this (using Save As utf8 in Notepad) as test.xls:

<html>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<table>
<tr>
  <th>id</th>
  <th>name</th>
</tr>
<tr>
 <td>4</td>
 <td>Hélène</td>
</tr>
</table>
</html>

This is just of a question of character encodings. It looks like you're exporting your data as UTF-8: é in UTF-8 is the two-byte sequence 0xC3 0xA9, which when interpreted in Windows-1252 is é. When you import your data into Excel, make sure to tell it that the character encoding you're using is UTF-8.


The CSV format is implemented as ASCII, not unicode, in Excel, thus mangling the diacritics. We experienced the same issue which is how I tracked down that the official CSV standard was defined as being ASCII-based in Excel.


Excel 2007 properly reads UTF-8 with BOM (EF BB BF) encoded csv.

Excel 2003 (and maybe earlier) reads UTF-16LE with BOM (FF FE), but with TABs instead of commas or semicolons.


I can only get CSV to parse properly in Excel 2007 as tab-separated little-endian UTF-16 starting with the proper byte order mark.


Writing a BOM to the output CSV file actually did work for me in Django:

def handlePersoonListExport(request):
    # Retrieve a query_set
    ...

    template = loader.get_template("export.csv")
    context = Context({
        'data': query_set,
    })

    response = HttpResponse()
    response['Content-Disposition'] = 'attachment; filename=export.csv'
    response['Content-Type'] = 'text/csv; charset=utf-8'
    response.write("\xEF\xBB\xBF")
    response.write(template.render(context))

    return response

For more info http://crashcoursing.blogspot.com/2011/05/exporting-csv-with-special-characters.html Thanks guys!


Another solution I found was just to encode the result as Windows Code Page 1252 (Windows-1252 or CP1252). This would be done, for example by setting Content-Type appropriately to something like text/csv; charset=Windows-1252 and setting the character encoding of the response stream similarly.


Note that including the UTF-8 BOM is not necessarily a good idea - Mac versions of Excel ignore it and will actually display the BOM as ASCII… three nasty characters at the start of the first field in your spreadsheet…


Check the encoding in which you are generating the file, to make excel display the file correctly you must use the system default codepage.

Wich language are you using? if it's .Net you only need to use Encoding.Default while generating the file.


If you have legacy code in vb.net like I have, the following code worked for me:

    Response.Clear()
    Response.ClearHeaders()
    Response.ContentType = "text/csv"
    Response.Expires = 0
    Response.AddHeader("Content-Disposition", "attachment; filename=export.csv;")
    Using sw As StreamWriter = New StreamWriter(Context.Response.OutputStream, System.Text.Encoding.Unicode)
        sw.Write(csv)
        sw.Close()
    End Using
    Response.End()

I've found a way to solve the problem. This is a nasty hack but it works: open the doc with Open Office, then save it into any excel format; the resulting .xls or .xlsx will display the accentuated characters.


With Ruby 1.8.7 I encode every field to UTF-16 and discard BOM (maybe).

The following code is extracted from active_scaffold_export:

<%                                                                                                                                                                                                                                                                                                                           
      require 'fastercsv'                                                                                                                                                                                                                                                                                                        
      fcsv_options = {                                                                                                                                                                                                                                                                                                           
        :row_sep => "\n",                                                                                                                                                                                                                                                                                                        
        :col_sep => params[:delimiter],                                                                                                                                                                                                                                                                                          
        :force_quotes => @export_config.force_quotes,                                                                                                                                                                                                                                                                            
        :headers => @export_columns.collect { |column| format_export_column_header_name(column) }                                                                                                                                                                                                                                
      }                                                                                                                                                                                                                                                                                                                          

      data = FasterCSV.generate(fcsv_options) do |csv|                                                                                                                                                                                                                                                                           
        csv << fcsv_options[:headers] unless params[:skip_header] == 'true'                                                                                                                                                                                                                                                      
        @records.each do |record|                                                                                                                                                                                                                                                                                                
          csv << @export_columns.collect { |column|                                                                                                                                                                                                                                                                              
            # Convert to UTF-16 discarding the BOM, required for Excel (> 2003 ?)                                                                                                                                                                                                                                     
            Iconv.conv('UTF-16', 'UTF-8', get_export_column_value(record, column))[2..-1]                                                                                                                                                                                                                                        
          }                                                                                                                                                                                                                                                                                                                      
        end                                                                                                                                                                                                                                                                                                                      
      end                                                                                                                                                                                                                                                                                                                        
    -%><%= data -%>

The important line is:

Iconv.conv('UTF-16', 'UTF-8', get_export_column_value(record, column))[2..-1]

open the file csv with notepad++ clic on Encode, select convert to UTF-8 (not convert to UTF-8(without BOM)) Save open by double clic with excel Hope that help Christophe GRISON

참고URL : https://stackoverflow.com/questions/155097/microsoft-excel-mangles-diacritics-in-csv-files

반응형