欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java导出文件之Excel(CSV)下并以流形式输出

程序员文章站 2022-06-01 14:09:46
...

<dependency>
		    <groupId>net.sourceforge.javacsv</groupId>
		    <artifactId>javacsv</artifactId>
		    <version>2.0</version>
		</dependency>  
@Test
    public void write(){
    try {
             // 创建CSV写对象
    List<Student> ls=new ArrayList<Student>();
             for (int i = 0; i <1000000; i++) {
            Student s=new Student();
            s.setName("小帅"+i);
            s.setAge(i);
            s.setScore("100"+i);
            s.setSex("男"+i);
            ls.add(s);
}
             //写入临时文件
             File tempFile = File.createTempFile("vehicle", ".csv");
             CsvWriter csvWriter = new CsvWriter(tempFile.getCanonicalPath(),',', Charset.forName("UTF-8"));
             // 写表头
             long s= System.currentTimeMillis();
             System.err.println();
             String[] headers = {"姓名","年龄","编号","性别"};
             csvWriter.writeRecord(headers);
             for (Student stu : ls) {
		csvWriter.write(stu.getName());
		csvWriter.write(stu.getAge()+"");
		csvWriter.write(stu.getScore());
		csvWriter.write(stu.getSex());
		csvWriter.endRecord();
		}
             csvWriter.close();
             long e=System.currentTimeMillis();

             System.err.println(e-s);;

   /**
    * 写入csv结束,写出流
    */
   java.io.OutputStream out = getResponse.getOutputStream();  
   byte[] b = new byte[10240];
   java.io.File fileLoad = new java.io.File(tempFile.getCanonicalPath());  
   getResponse.reset();
   getResponse.setContentType("application/csv");  
   getResponse.setHeader("content-disposition", "attachment; filename=vehicleModel.csv");  
	long fileLength = fileLoad.length();  
	String length1 = String.valueOf(fileLength);  
	getResponse.setHeader("Content_Length", length1);  
	java.io.FileInputStream in = new java.io.FileInputStream(fileLoad);  
	int n;  
	while ((n = in.read(b)) != -1) {  
  	 out.write(b, 0, n); //每次写入out1024字节 
	}  
  	 in.close();  
  	 out.close(); 

         } catch (IOException e) {
             e.printStackTrace();
         }
    }

网上找太多,眼逗看累了。自己写个简单的 

java导出文件之Excel(CSV)下并以流形式输出

参考文章:http://blog.csdn.net/loongshawn/article/details/53423121

ps:version我本地只能用2.0;以流的形式写出游览器不用做操作文件会直接下载;

2:因为csvWriter不提供类似Poi的写入流  workbook.write(out);故在csv写入数据完之后,要手动把文件写入流;

java导出文件之Excel(CSV)下并以流形式输出

相关标签: csv