1.Maven依赖
//用的是javacsv开源工具
<dependency>
<groupId>net.sourceforge.javacsvgroupId>
<artifactId>javacsvartifactId>
<version>2.0version>
dependency>
<dependency>
<groupId>commons-collectionsgroupId>
<artifactId>commons-collectionsartifactId>
<version>3.2.2version>
dependency>
<dependency>
<groupId>commons-langgroupId>
<artifactId>commons-langartifactId>
<version>2.6version>
dependency>
2.工具类
import com.csvreader.CsvWriter;
import org.apache.commons.collections.CollectionUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
/**
* Created by John on 2017/12/30.
*/
public class CsvUtil {
public static void main(String[] args) {
String filePath = "D://study.csv";
CsvWriter csvWriter = new CsvWriter(filePath, ',', Charset.forName("GBK"));
// 写表头
String[] headers = {"编号", "姓名", "年龄"};
String[] content = {"12365", "张山", "34"};
try {
csvWriter.writeRecord(headers);
csvWriter.writeRecord(content);
} catch (IOException e) {
e.printStackTrace();
}
csvWriter.close();
}
/**
* 导出.csv文件在浏览器端下载(可选择保存路径)
*
* @param fileName 文件名
* @param columnKeyMap 列名-属性,这里用LinkedHashMap是为了保证导出去的Excel列名顺序不会乱
* @param dataList 数据源
* @param response HttpServletResponse
*/
public static void writeData(String fileName, LinkedHashMap columnKeyMap, List
3.使用示例
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
/**
* Created by John on 2017/12/30.
*/
@Controller
@EnableAutoConfiguration
public class SampleController {
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
@RequestMapping("/csv")
public void csv(HttpServletResponse response){
// 创建CSV写对象
List> ls=new ArrayList<>();
/*for (int i = 0; i <10000; i++) {
Student s=new Student();
s.setName("小帅"+i);
s.setAge(i);
s.setScore("100"+i);
s.setSex("男"+i);
ls.add(s);
}*/
Map map = null;
for (int i=0;i<100000;i++){
map = new HashMap<>();
map.put("name","你妹" + i);
map.put("age",i);
map.put("score",i);
map.put("sex","男");
ls.add(map);
}
String fileName = "vehicle";
LinkedHashMap keyMap = new LinkedHashMap<>();
keyMap.put("name","姓名");
keyMap.put("age","年龄");
keyMap.put("score","编号");
keyMap.put("sex","性别");
long start = System.currentTimeMillis();
CsvUtil.writeData(fileName,keyMap,ls,response);
System.out.println("耗时:" + (System.currentTimeMillis() - start) + "ms");
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}