[英]Java create csv file, has " and ; in it, open correctly in Excel
需要使用以下文本创建csv文件:
<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();
它创建了文件,但是由于某种原因我无法在Excel中打开它,当我打开它时,它只给我空白文件,没有文本。 主要问题是“;” 在文本中间。 它用作单元格分隔符,并将文本分隔在另一个单元格中,但是我需要将其保留在一个单元格中。
当我直接在excel中创建文件时,它可以正常工作。 它甚至忽略了“;” 和文本保留在一个单元格中。 到目前为止,答案是,可能是由于编码错误所致,应该为UTF-8,但这应该可以。
您的内容不允许包含保留字符,例如分号。 为了解决这个问题,您可以使用双引号。
此答案总结了如何以及何时在.csv中定界和双引号
如果您创建的CSV用于excel,为什么不考虑使用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的示例页面 。 此示例显示了如何在单元格上添加边框,但同时也演示了创建工作簿并将内容放入其中的简便性。 而且,您不必担心像古怪的怪癖,例如转义分号或将来可能出现的其他怪异现象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.