我的应用程序将数据从Jtable写入一个csv文件。
我使用以下功能:
public static boolean exportToCSV(JTable RnRFetchTable,String pathToExportTo) {
try {
DateFormat writeDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
Date writeDate = new Date();
TableModel model = RnRFetchTable2.getModel();
FileWriter csv = new FileWriter(new File("C:/Users/Desktop/TableExport" + writeDateFormat.format(writeDate) + ".csv"));
for (int i = 0; i < model1.getColumnCount(); i++) {
csv.write(model1.getColumnName(i) + ",");
}
csv.write("\n");
for (int i = 0; i < model1.getRowCount(); i++) {
for (int j = 0; j < model1.getColumnCount(); j++) {
csv.write(model1.getValueAt(i, j).toString() + ",");
}
csv.write("\n");
}
csv.close();
JOptionPane.showMessageDialog(null,"Export Successful!");
return true;
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,"Error! Excel cannot be exported!");
}
return false;
}
当其中一列没有逗号时,此代码可以正常工作,但是当它包含逗号时,定界发生在“,”出现的任何地方。如何通过转义逗号来编写csv?
答案 0 :(得分:0)
您可以在文本两边加上双引号:
csv.write("\"" + model1.getValueAt(i, j).toString() + "\",");