Java创buildcsv文件,具有“和;在其中,在Excel中正确打开

需要用这个文本创buildcsv文件:

<p><span style="color: #000000;"><strong>TEXT: </strong></span>another TEXT</strong></span> 

这是我的代码:

 PrintWriter testFile = new PrintWriter("C:\\JAVA\\test01.csv", "UTF-8"); String test = "<p><span style=\"color: #000000;\"><strong>Dostupnosť: </strong></span>do 2 -14 dní</strong></span>"; testFile.print("zero;one;"+test); testFile.close(); 

它创build的文件,但我不能由于某种原因打开它在Excel中,当我打开它,它只给我空白文件,没有文字。 主要的问题是,“;” 在文本的中间。 它用作单元格分隔符并将文本分隔到另一个单元格中,但是我需要将其保留在一个单元格中。

当我在Excel中直接创build文件时,它工作正常。 它甚至无视“;” 文本仍然在一个单元格中。 到目前为止的答案是,这可能是因为错误的编码,它应该是UTF-8,但应该没问题。

您的内容不允许包含保留字符,如分号。 为了解决这个问题,你可以使用双引号。

这个答案总结了在.csv中如何以及何时分隔和双引号

如果你在excel中创build一个CSV文件,为什么不考虑使用类似于Apach POI的东西呢? 如果你花费太多的时间来寻找一个写入CSV的工作,这个库可以为你解决这个问题。 这很容易实现。 这是一个代码示例:

 import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.*; import java.io.FileOutputStream; /** * Working with borders */ public class WorkingWithBorders { public static void main(String[] args) throws Exception { Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); Sheet sheet = wb.createSheet("borders"); // Create a row and put some cells in it. Rows are 0 based. Row row = sheet.createRow((short) 1); // Create a cell and put a value in it. Cell cell = row.createCell((short) 1); cell.setCellValue(4); // Style the cell with borders all around. CellStyle style = wb.createCellStyle(); style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.GREEN.getIndex()); style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLUE.getIndex()); style.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); cell.setCellStyle(style); // Write the output to a file FileOutputStream fileOut = new FileOutputStream("xssf-borders.xlsx"); wb.write(fileOut); fileOut.close(); } } 

这是来自Apache的示例页面 。 这个展示了如何将边框放在单元格上,但是也展示了创build工作簿和将东西放入其中的过程。 而且你不必担心怪异的怪癖,比如逃避分号或者将来可能出现的其他任何古怪事物。