简体   繁体   中英

What encoding should be used when we make a downloadable file from a J2EE Modern Web App?

I 'm working on Mac Os with Eclipse Kepler on a JSF java project .

How to make a file downloadable for a Windows, Mac Os, Linux environements without misinterpreted characters because of encoding and plat-forms ?

Do we need to check which os the client use to adapt encoding with user-agent parsing ?

If you use UTF-8 , it will be ok on Unix Based Os, but how to make it open simply in windows with excel?

I write this code to export in UTF-8. But it will misinterpreted é & è in Excel.

FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();

ec.responseReset();
ec.setResponseContentType("text/csv"); 
ec.setResponseCharacterEncoding("UTF-8");

String fileName = "CleanOmicsTracer_Tableau_"+type+".csv";

ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); 

// Now you can write the InputStream of the file to the above OutputStream the usual way.

BufferedOutputStream csvOut = new BufferedOutputStream(ec.getResponseOutputStream());  
BufferedWriter csvWriter = new BufferedWriter(new OutputStreamWriter(csvOut, "UTF-8"));

        csvWriter.append("Etude;Identifiant Analyse;Numero d'inclusion;Identifiant Prelevement;Identifiant Extrait;Technologie;Service;Sous-analyses;Categorie;Date Enregistrement\n");

        for (AnalyseDispatcher aAnalyse : viewedListAnalyse) { // somethings is your List<Something>

            csvWriter
            .append(toCsvField(aAnalyse.getSample().getParticipant().getProject().getStudy_name()))
            .append(';')
            .append(toCsvField("A"+aAnalyse.getId()))
            .append(';').append(toCsvField(aAnalyse.getSample().getParticipant().getId_study()))   .append('\n'); 
         } 
         csvWriter.flush();
         csvWriter.close();
         csvOut.close();

         fc.responseComplete(); 
        }

What is the source of the CSV character stream?

  • A file?
  • A blob in a database?

You need to make sure that the java.io.Reader that is reading the file uses correct encoding (ie the initial file's encoding).

Try:

ec.setResponseContentType("text/csv;charset=UTF-8");

or

ec.setResponseContentType("application/csv;charset=UTF-8");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM