java导出csv格式文件的方法
程序员文章站
2022-04-02 22:58:10
本文实例为大家分享了java导出csv格式文件的具体代码,供大家参考,具体内容如下导出csv格式文件的本质是导出以逗号为分隔的文本数据import java.io.bufferedwriter; im...
本文实例为大家分享了java导出csv格式文件的具体代码,供大家参考,具体内容如下
导出csv格式文件的本质是导出以逗号为分隔的文本数据
import java.io.bufferedwriter; import java.io.file; import java.io.fileinputstream; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.io.outputstreamwriter; import java.net.urlencoder; import java.util.arraylist; import java.util.iterator; import java.util.linkedhashmap; import java.util.list; import java.util.map; import javax.servlet.http.httpservletresponse; import com.alibaba.druid.util.stringutils; /** * 文件操作 */ public class csvutils { /** * 功能说明:获取utf-8编码文本文件开头的bom签名。 * bom(byte order mark),是utf编码方案里用于标识编码的标准标记。例:接收者收到以ef bb bf开头的字节流,就知道是utf-8编码。 * @return utf-8编码文本文件开头的bom签名 */ public static string getbom() { byte b[] = {(byte)0xef, (byte)0xbb, (byte)0xbf}; return new string(b); } /** * 生成cvs文件 * @param exportdata * 源数据list * @param map * csv文件的列表头map * @param outputpath * 文件路径 * @param filename * 文件名称 * @return */ @suppresswarnings("rawtypes") public static file createcsvfile(list exportdata, linkedhashmap map, string outputpath, string filename) { file csvfile = null; bufferedwriter csvfileoutputstream = null; try { file file = new file(outputpath); if (!file.exists()) { file.mkdirs(); } //定义文件名格式并创建 csvfile =new file(outputpath+filename+".csv"); file.createnewfile(); // utf-8使正确读取分隔符"," //如果生产文件乱码,windows下用gbk,linux用utf-8 csvfileoutputstream = new bufferedwriter(new outputstreamwriter(new fileoutputstream( csvfile), "utf-8"), 1024); //写入前段字节流,防止乱码 csvfileoutputstream.write(getbom()); // 写入文件头部 for (iterator propertyiterator = map.entryset().iterator(); propertyiterator.hasnext();) { java.util.map.entry propertyentry = (java.util.map.entry) propertyiterator.next(); csvfileoutputstream.write((string) propertyentry.getvalue() != null ? (string) propertyentry.getvalue() : "" ); if (propertyiterator.hasnext()) { csvfileoutputstream.write(","); } } csvfileoutputstream.newline(); // 写入文件内容 for (iterator iterator = exportdata.iterator(); iterator.hasnext();) { object row = (object) iterator.next(); for (iterator propertyiterator = map.entryset().iterator(); propertyiterator .hasnext();) { java.util.map.entry propertyentry = (java.util.map.entry) propertyiterator .next(); string str=row!=null?((string)((map)row).get( propertyentry.getkey())):""; if(stringutils.isempty(str)){ str=""; }else{ str=str.replaceall("\"","\"\""); if(str.indexof(",")>=0){ str="\""+str+"\""; } } csvfileoutputstream.write(str); if (propertyiterator.hasnext()) { csvfileoutputstream.write(","); } } if (iterator.hasnext()) { csvfileoutputstream.newline(); } } csvfileoutputstream.flush(); } catch (exception e) { e.printstacktrace(); } finally { try { csvfileoutputstream.close(); } catch (ioexception e) { e.printstacktrace(); } } return csvfile; } /** * 生成并下载csv文件 * @param response * @param exportdata * @param map * @param outputpath * @param filename * @throws ioexception */ @suppresswarnings("rawtypes") public static void exportdatafile(httpservletresponse response,list exportdata, linkedhashmap map, string outputpath,string filename) throws ioexception{ file csvfile = null; bufferedwriter csvfileoutputstream = null; try { file file = new file(outputpath); if (!file.exists()) { file.mkdirs(); } //定义文件名格式并创建 csvfile =new file(outputpath+filename+".csv"); if(csvfile.exists()){ csvfile.delete(); } csvfile.createnewfile(); // utf-8使正确读取分隔符"," //如果生产文件乱码,windows下用gbk,linux用utf-8 csvfileoutputstream = new bufferedwriter(new outputstreamwriter(new fileoutputstream(csvfile), "utf-8"), 1024); //写入前段字节流,防止乱码 csvfileoutputstream.write(getbom()); // 写入文件头部 for (iterator propertyiterator = map.entryset().iterator(); propertyiterator.hasnext();) { java.util.map.entry propertyentry = (java.util.map.entry) propertyiterator.next(); csvfileoutputstream.write((string) propertyentry.getvalue() != null ? (string) propertyentry.getvalue() : "" ); if (propertyiterator.hasnext()) { csvfileoutputstream.write(","); } } csvfileoutputstream.newline(); // 写入文件内容 for (iterator iterator = exportdata.iterator(); iterator.hasnext();) { object row = (object) iterator.next(); for (iterator propertyiterator = map.entryset().iterator(); propertyiterator .hasnext();) { java.util.map.entry propertyentry = (java.util.map.entry) propertyiterator .next(); string str=row!=null?((string)((map)row).get( propertyentry.getkey())):""; if(stringutils.isempty(str)){ str=""; }else{ str=str.replaceall("\"","\"\""); if(str.indexof(",")>=0){ str="\""+str+"\""; } } csvfileoutputstream.write(str); if (propertyiterator.hasnext()) { csvfileoutputstream.write(","); } } if (iterator.hasnext()) { csvfileoutputstream.newline(); } } csvfileoutputstream.flush(); } catch (exception e) { e.printstacktrace(); } finally { try { csvfileoutputstream.close(); } catch (ioexception e) { e.printstacktrace(); } } inputstream in = null; try { in = new fileinputstream(outputpath+filename+".csv"); int len = 0; byte[] buffer = new byte[1024]; outputstream out = response.getoutputstream(); response.reset(); response.setcontenttype("application/csv;charset=utf-8"); response.setheader("content-disposition","attachment; filename=" + urlencoder.encode(filename+".csv", "utf-8")); response.setcharacterencoding("utf-8"); while ((len = in.read(buffer)) > 0) { out.write(new byte[] { (byte) 0xef, (byte) 0xbb, (byte) 0xbf }); out.write(buffer, 0, len); } out.close(); } catch (filenotfoundexception e) { } finally { if (in != null) { try { in.close(); } catch (exception e) { throw new runtimeexception(e); } } } } /** * 删除该目录filepath下的所有文件 * @param filepath * 文件目录路径 */ public static void deletefiles(string filepath) { file file = new file(filepath); if (file.exists()) { file[] files = file.listfiles(); for (int i = 0; i < files.length; i++) { if (files[i].isfile()) { files[i].delete(); } } } } /** * 删除单个文件 * @param filepath * 文件目录路径 * @param filename * 文件名称 */ public static void deletefile(string filepath, string filename) { file file = new file(filepath); if (file.exists()) { file[] files = file.listfiles(); for (int i = 0; i < files.length; i++) { if (files[i].isfile()) { if (files[i].getname().equals(filename)) { files[i].delete(); return; } } } } } /** * 测试数据 * @param args */ @suppresswarnings({ "rawtypes", "unchecked" }) public static void main(string[] args) { list exportdata = new arraylist<map>(); map row1 = new linkedhashmap<string, string>(); row1.put("1", "11"); row1.put("2", "12"); row1.put("3", "13"); row1.put("4", "14"); exportdata.add(row1); row1 = new linkedhashmap<string, string>(); row1.put("1", "21"); row1.put("2", "22"); row1.put("3", "23"); row1.put("4", "24"); exportdata.add(row1); linkedhashmap map = new linkedhashmap(); //设置列名 map.put("1", "第一列名称"); map.put("2", "第二列名称"); map.put("3", "第三列名称"); map.put("4", "第四列名称"); //这个文件上传到路径,可以配置在数据库从数据库读取,这样方便一些! string path = "e:/"; //文件名=生产的文件名称+时间戳 string filename = "文件导出"; file file = csvutils.createcsvfile(exportdata, map, path, filename); string filename2 = file.getname(); system.out.println("文件名称:" + filename2); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。