首页 > 代码库 > 把一个txt文件转化为带标题栏的Excel文档

把一个txt文件转化为带标题栏的Excel文档

public class Export {
	public static final String CSVNAME_COMPETITION="cpc.csv";
}


public class CSV {
	public static final String ENDLINE = "\n";
	public static final Map<String,String> HEADLINES=new HashMap<String,String>();
	
	static{
	//分别是Excel文档的第一行标题内容
		HEADLINES.put(Export.CSVNAME_COMPETITION, formatToCSV("1","2","3","4","5"));
	}
	
	public static String formatToCSV(Object...params){
		StringBuilder sb=new StringBuilder("\""+params[0]+"\"");
		
		for(int i=1;i<params.length;i++)
		{
			sb.append(",");
			if(params[i] instanceof Double && ((Double)params[i]).isInfinite())
			{
				sb.append("\"0.0\"");
			}else{
				sb.append("\""+params[i]+"\"");
			}
		}
		sb.append(ENDLINE);
		return sb.toString();
	}
	
	public static String getHeadLine(String fileName)
	{
		return HEADLINES.get(fileName);
	}
}

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class OutPut {
	public static BufferedWriter getWriter(String name,String path){
		BufferedWriter  br = null;
		try {
			mkdirs(path);
			File file = new File(path+"/"+ name);
			br = new BufferedWriter(new FileWriter(file));
			//if(!file.exists()){
			//这里要注意下,通常我们再把txt转化问Excel,由于编码格式的原因,一定要添加上下面这一行,而且只能添加在开头。
				br.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF }));   
			//}
			br.write(new String(CSV.getHeadLine(name).getBytes("utf-8")));
			br.flush();
			//br.close();
		} catch (IOException e) {
			e.printStackTrace(); 
		}
		return br;
	}
	
	public static void mkdirs(String path)
	{
		File f=new File(path);
		if(!f.isDirectory())
			f.delete();
		if(!f.exists())
			f.mkdirs();
	}
}

@Test
	public void excel() throws IOException{
		Writer writer = OutPut.getWriter(Export.CSVNAME_COMPETITION, "E:/testexcel");
		writer.write(CSV.formatToCSV("对手","数量","广告","关键"));
		writer.close();
	}


把一个txt文件转化为带标题栏的Excel文档