Java 导出CSV文件及实现web下载CSV

本文主要介绍Java 导出CSV文件到本地及实现web下载CSV。


1.Java 导出CSV文件到本地

csvWriter:

package com.csvio;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;


public class CsvWriter extends BufferedWriter {

	/**
	 * set wirter
	 * 
	 * @param out writer
	 */
	public CsvWriter(final Writer out) {
		super(out);
	}

	/**
	 * csv Write line
	 * 
	 * @param csvLine
	 *            csv line
	 * @throws IOException IOException
	 */
	public void writeLine(final List<String> csvLine) throws IOException {
		StringBuffer sb = new StringBuffer();
		
		for (int i = 0; i < csvLine.size(); i++) {
			String line = csvLine.get(i);
			if (line == null) {
				line = "";
			}
			sb.append("\"").append(line.replaceAll("\"", "\"\"")).append("\",");
		}
		
		super.write(sb.deleteCharAt(sb.length() - 1).toString());
		super.newLine();
	}

}


Student.java

package com.csvio;

public class Student {

    private String name;

    private String sex;
    private int age;

    public Student() {
    }

    public Student(String name, String sex, int age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public String getSex() {
        return sex;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student [toString()=" + this.name + "-->" + this.sex + "-->"
                + this.age + "]";
    }
}

client:

package com.csvio;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class CsvClient {

    /**
     * @param args
     */
    public static void main(String[] args) {
        File file = getFile();

        List<Student> stooges = new ArrayList<Student>();
        for (int i=0;i<5;i++){
            Student stu = new Student();
            stu.setAge(i+10);
            stu.setName("name " +i);
            stu.setSex(i/2==0 ?"boy":"girl");
            stooges.add(stu);
        }

         CsvWriter cw = null;

         try {
// J2EE Web下载时为下面注释的代码,传人的参数是HttpServletResponse
//            cw = new CsvWriter(response.getWriter());
            cw = new CsvWriter(new PrintWriter(file));
            for (Student stu : stooges) {
                cw.writeLine(getCsvLine(stu));
            }
            cw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (cw != null) {
                    cw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println("Done.");
    }

    private static List<String> getCsvLine(Student stu) {
        List<String> csvLine = new ArrayList<String>();
        csvLine.add(stu.getName());
        csvLine.add(Integer.toString(stu.getAge()));
        csvLine.add(stu.getSex());
        return csvLine;
    }

    private static File getFile() {
        String path = "E:\\test\\";
        String filename="abc.csv";

        File directory = new File(path);
        if (!directory.exists())
            directory.mkdirs();
        File file = new File(path + filename);
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return file;
    }

}


2. web下载CSV
web下载csv的原理和输出到本地一致,就是将HttpServletResponse的流内容(writer)写入到浏览器,前提是该response的header中content-Type要告诉浏览器以下载模式接受,具体参数参见http://blog.csdn.net/bluefish625/article/details/6659288 。



  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Spring Boot中导出CSV文件可以使用以下步骤: 1. 添加依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>5.5.2</version> </dependency> ``` 2. 创建CSV数据 可以使用Java集合或者数据库查询结果等数据源来创建CSV文件数据,例如: ```java List<String[]> data = new ArrayList<>(); data.add(new String[]{"Name", "Age", "Email"}); data.add(new String[]{"John Doe", "30", "[email protected]"}); data.add(new String[]{"Jane Doe", "25", "[email protected]"}); ``` 3. 导出CSV文件 可以使用以下代码将数据导出CSV文件: ```java CsvWriter csvWriter = new CsvWriter(new FileWriter("data.csv"), CsvWriter.DEFAULT_SEPARATOR, CsvWriter.NO_QUOTE_CHARACTER); for (String[] rowData : data) { csvWriter.writeNext(rowData); } csvWriter.close(); ``` 其中,CsvWriter是opencsv库提供的CSV写入器,接受一个Writer对象作为参数,用于将数据写入文件中。 4. 下载CSV文件 可以使用Spring Boot的ResponseEntity来将CSV文件返回给客户端下载,例如: ```java @GetMapping("/download") public ResponseEntity<Resource> downloadCsvFile() throws IOException { File file = new File("data.csv"); InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=data.csv"); return ResponseEntity.ok() .headers(headers) .contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(resource); } ``` 其中,InputStreamResource是Spring的Resource接口的实现,用于将文件转换为InputStream对象。将其包装在ResponseEntity中返回给客户端即可。 完整示例代码: ```java import com.opencsv.CSVWriter; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Controller @RequestMapping("/csv") public class CsvController { @GetMapping("/export") @ResponseBody public ResponseEntity<Resource> exportCsvFile() throws IOException { List<String[]> data = new ArrayList<>(); data.add(new String[]{"Name", "Age", "Email"}); data.add(new String[]{"John Doe", "30", "[email protected]"}); data.add(new String[]{"Jane Doe", "25", "[email protected]"}); CsvWriter csvWriter = new CsvWriter(new FileWriter("data.csv"), CsvWriter.DEFAULT_SEPARATOR, CsvWriter.NO_QUOTE_CHARACTER); for (String[] rowData : data) { csvWriter.writeNext(rowData); } csvWriter.close(); File file = new File("data.csv"); InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=data.csv"); return ResponseEntity.ok() .headers(headers) .contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(resource); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值