package com.study.csv;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
/**
* <p>添加类描述</p>
*
* @author chentao
* @version v 0.1 2021/1/17 20:46
*/
public class CsvTest {
public static void main(String[] args) {
testWriteBasicCsv();
//https://www.jb51.net/article/47963.htm
}
private static void testWriteBasicCsv() {
File file = new File("F:\\test\\test1.csv");
try {
FileOutputStream out = new FileOutputStream(file);
String row1="name,age";
//换行
String rn="\r\n";
String row2="tom,12";
out.write(row1.getBytes("GBK"));
out.write(rn.getBytes("GBK"));
out.write(row2.getBytes("GBK"));
//最近写了一个生成csv的程序,生成的csv其中有一列数字长度为13位,csv中查看没有问题,但是用excel打开数字就会变成科学计数法
//
//解决办法:
//1、在生成csv的时候,在数字的前面或后面加上"\t"制表符,再用excel打开问题解决!如 “1234567890 ”
out.write("\n".getBytes("GBK"));
String row3="12345678901234567890";
out.write(row3.getBytes("GBK"));
out.write("\n".getBytes("GBK"));
String row4="2222,\t12345678901234567890";
out.write(row4.getBytes("GBK"));
out.write("\n".getBytes("GBK"));
//一般如果有参数赋值这样方便一点,不用拼接字符串
String row5Pattern = "\t{0},\t{1}r\n";
Object[] row5Date = new Object[]{"\t张三", "\t" + "王五"};
out.write(MessageFormat.format(row5Pattern, row5Date).getBytes("GBK"));
//金额数字MessageFormat.format
String row6Pattern = "{0},\t{1}r\n";
Object[] row6Date = new Object[]{MessageFormat.format("{0,number,0.00}",100), "\t" + "王五"};
out.write(MessageFormat.format(row6Pattern, row6Date).getBytes("GBK"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
生成csv
最新推荐文章于 2024-09-08 00:06:54 发布