Open CharlsLin opened 4 years ago
import com.google.common.io.Files;
File file= null;
String fileName = null;
file = new File(Files.createTempDir(), fileName );
创建一个CSVBean.java,写入要输出到CSV文件的属性,比如说id, name, age, sex.... 可通过各种注释来设置文件头部内容,比如:
//不设置头部
@CsvEntity(header = false)
public class CSVBean{
//csv文件的列
@CsvColumn
private String name;
@CsvColumn
private String id;
...
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id= id;
}
}
2. 创建一个 CSVBeanService.java,用于取得数据,并设置到CSVBean类属性里去。
```java
@Service
public class CSVBeanService{
@Autowired
UserService uSerService;
public List<CSVBean>createCsvList(List<User>list, String Param1,String Param2) {
List<CSVBean > csvList= new ArrayList<CSVBean >();
//循环赋值
for (User user: list) {
//创建新的一条数据
CSVBean cb = new CSVBean();
cb.setId(uSerService.findById(Param1));
cb.setName(Param2);
...
}
return csvList;
}
}
@Controller public class downLoadController{
@Autowired CSVBeanService cSVBeanService;
private String download(List
File file = null;
String fileName = null;
//生成cookie的key和value
Cookie cookie = new Cookie("downloaded", "yes");
cookie.setPath("/");
// 内容设置
file = File.createTempFile("download", "tmp");
CsvIOUtil.writeCsv(file, CsvList , "\r\n", ',', true, CSVBean .class);
// response設定
res.setCharacterEncoding("Windows-31J");
res.setContentType( "application/octet-stream"+ ";charset="+ "Windows-31J");
res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
res.setHeader("Cache-Control", "no-store");
res.setHeader("Pragma", "no-cache");
res.addHeader("Content-Length", String.valueOf(file.length()));
FileUtils.copyFile(file, res.getOutputStream());
res.getOutputStream().flush();
} }
4. 下载完成后刷新页面(js)
```javascript
setInterval(function() {
var value = GetCookie("downloaded");
if (value == "yes") {
setTimeout(function() {
window.location.href = 下载完成后调用的action;
}, 1000);//👈设置timeout
}
deleteCookie("downloaded");
}, 1000);//👈设置timeout
ArrayList of Files ⇒ ZIP ダウンロード
https://www.jianshu.com/p/7cabe09ce563