univocity-parsers列写内容缺失前缀0

daiyongcai 2017-08-02 11:05:12

请教下输入数字或者金额的列怎么设置文本格式,使其原样写入csv文件中
Object[] r = {"'0000001111","3000.00"};
写入后的csv想要的效果是
真实结果:
h1 h2
1111 3000
1111 3000

想要的结果为:
结果:
h1 h2
0000001111 3000.00
0000001111 3000.00


以下是测试是源码
public static void createCSVFile(String[] heads, List<Object[]> rows, String outPutPath)
{
// CsvWriter (and all other file writers) work with an instance of
// java.io.Writer
File csvFile = new File(outPutPath);
File parent = csvFile.getParentFile();
if (parent != null && !parent.exists())
{
parent.mkdirs();
}
try
{
csvFile.createNewFile();
// By default, only values that contain a field separator are enclosed within quotes.
// If quotes are part of the value, they are escaped automatically as well. Empty rows are discarded automatically.
// Set the field delimiter to ';', the default value is ','
CsvWriterSettings settings = new CsvWriterSettings();
CsvFormat format = settings.getFormat();
format.setDelimiter(',');
CsvWriter writer = new CsvWriter(csvFile, "GBK", settings);
// Write the record headers of this file
writer.writeHeaders(heads);

// Write contents and close the given output Writer instance.
writer.writeRowsAndClose(rows);
} catch (Exception e)
{
e.printStackTrace();
log.error(e.getMessage());
}
}

public static void main(String[] args)throws Exception {
String filePath = "C:/test/test.csv";
String[] headers = {"h1","h2"};
List<Object[]> rows = new ArrayList<Object[]>();
for (int i=0; i <2 ;i++) {
Object[] r = {"'0000001111","3000.00"};
rows.add(r);
}
try {
List<Map<String,Object>> results = null;
createCSVFile(headers, rows, filePath);
} catch (Exception e) {
e.printStackTrace();
}
}


...全文
169 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
daiyongcai 2017-08-07
  • 打赏
  • 举报
回复
java使用univocity-parsers生成csv,受csv格式的限制,填充的内容会失真,如浮点型,长数字字符串, Object[] r = {"0000001111",3000.00,"11111232222343434"}; ————》 1111 3000 1.11112E+16 1111 3000 1.11112E+16 写入数据前,进行 ="内容" 封装。 Object[] r = {"=\"0000001111\"","=\"3000.00\"","=\"11111232222343434\""}; ————》 0000001111 3000.00 11111232222343434 0000001111 3000.00 11111232222343434 暂时用这种方法取巧解决,这个不是最好的解决方案, 不知道用univocity-parsers怎么设置列属性,这个才是最优的解决方案,后续在研究。

51,410

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧