I'm trying to write a csv-file from java. Works perfectly, but when I write e.g. 19,4 to csv-file, in excel it is shown as 19. April. So I put a \' in front of 19,4. Value is shown as number now, but I have the ' in front of it. When I click into the column in excel and enter => the ' vanishes. What do I have to do, that the ' is not shown from beginning?
Here is some example source (from a servlet):
public void doWork(HttpServletRequest request, HttpServletResponse response) {
byte[] fileData = null;
String buffer = "";
buffer += "First";
buffer += ";";
buffer += "\'";
buffer += "19,4";
buffer += ";";
buffer += "\n";
buffer += "Second";
buffer += ";";
buffer += "\'";
buffer += "15,1";
buffer += ";";
buffer += "\n";
buffer += "Third";
buffer += ";";
buffer += "\'";
buffer += "1,7";
buffer += ";";
buffer += "\n";
fileData = buffer.getBytes("UTF-8");
byte[] fileDataWithBOM = new byte[fileData.length+10];
fileDataWithBOM[0] = (byte)0xef;
fileDataWithBOM[1] = (byte)0xbb;
fileDataWithBOM[2] = (byte)0xbf;
System.arraycopy(fileData, 0, fileDataWithBOM, 3, fileData.length);
ServletOutputStream out = null;
String fileName = "Accounting.csv";
try {
response.setContentType("text/csv");
String disposition = "attachment; fileName="+fileName;
response.setHeader("Content-Disposition", disposition);
response.setCharacterEncoding("UTF-8");
out = response.getOutputStream();
int length = fileData.length;
response.setContentLength(length);
out.write(fileData);
out.flush();
out.close();
} catch (Exception e) {
throw e;
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}