BufferedWriter 将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。 可以指定缓冲区的大小,或者接受默认的大小。在大多数情况下,默认值就足够大了
//导出数据
function exportData(){
var data = {};
if($("#memberName").val()) data.memberName = $("#memberName").val();
if($("#merberTel").val()) data.merbertel = $("#merberTel").val();
//创建标签元素
var form = document.createElement('form')
form.style.display = 'none'
document.body.appendChild(form)
form.method = 'POST'
form.action = "${webroot}/admin/exportDB.do"; //url
form.enctype = 'application/x-www-form-urlencoded'
var dataEl = document.createElement('input');
dataEl.type = 'hidden';
dataEl.name = 'data';
dataEl.value = JSON.stringify(data); //转JSON
form.appendChild(dataEl)
form.submit()
form.target = '_blank'
}
以上无非就是创建下面的一个标签(看懂的可以略过),作这一步的目的是可以只导出自己查询出来的列表:
导出其实和页面查询 有类似,input标签中的value存放数据data
需要了解form表单中target属性和enctype属性,前往另一篇博客
博客地址:https://blog.csdn.net/tt336798/article/details/81538649
导包
import java.io.BufferedWriter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.io.output.FileWriterWithEncoding;
声明变量
//导出地址
private String rootPath="E:/excelFiles/";
//产生的文件名
private String tempName="member";
导出方法(查询导出表所有的数据)
/**
* 导出数据
* @param request
* @param response
* @return
*/
@SuppressWarnings("unchecked")
@RequestMapping("/exportDB")
@ResponseBody
public void exportMember(HttpServletRequest request, HttpServletResponse response){
RequestModel requestModel=BaseUtil.getModel(request, response);
Map map=memberServiceImpl.exportData(requestModel.getData(),null);
List list = new ArrayList();
if (map.get("data") != null) {
list = (List) map.get("data"); //map 转list
}
try {
downLoad(list, "member", response); //方法如下
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这里的map,也就是从数据库中获取的所有数据,我后面转成了list。每个项目的框架不同,代码编写上也会也所不同。转回话题,在这一步中是获取你需要导出的数据表格,是导出所有数据,这里不用分页。
private void downLoad(List list, String fileName, HttpServletResponse response) throws IOException {
long time = new Date().getTime();
File file = new File(rootPath+ time + ".csv");
BufferedWriter bw = new BufferedWriter(new FileWriterWithEncoding(file, "gb2312"));
bw.write("昵称,姓名,手机号码,性别,年龄,邮箱");
bw.write("\n");
for (MemberEntity member : list) {
bw.write((StringUtils.isBlank(member.getNickName()) ? "-" : member.getNickName()) + ",");
bw.write((StringUtils.isBlank(member.getMemberName()) ? "-" : member.getMemberName()) + ",");
bw.write((StringUtils.isBlank(member.getMerberTel()) ? "-" : member.getMerberTel()) + ",");
if(member.getSex()==1){ //男
bw.write((StringUtils.isBlank(member.getSex.toString()) ? "-" : "男") + ",");
}else{
bw.write((StringUtils.isBlank(member.getSex().toString()) ? "-" : "女") + ",");
}
if(member.getSex()==0){ //女
bw.write((StringUtils.isBlank(member.getSex().toString()) ? "-" : "女") + ",");
}else{
bw.write((StringUtils.isBlank(member.getSex().toString()) ? "-" : "男") + ",");
}
bw.write((StringUtils.isBlank(member.getAge().toString()) ? "-" : member.getAge().toString()) + ",");
bw.write((StringUtils.isBlank(member.getMail().toString()) ? "-" : member.getMail().toString()) + ",");
bw.write("\n");
}
bw.close();
ExcelUtil.downloadCsv(file, response, fileName);
}
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
public static void downloadCsv(File file, HttpServletResponse response,String filename) {
try {
// path是指欲下载的文件的路径。
// File file = new File(path);
// 取得文件名。
// String filename = file.getName();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(filename, "UTF-8") + ".csv"); //.csv 或则 .xls
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=gb2312");
toClient.write(buffer);
toClient.flush();
toClient.close();
// file.delete();
} catch (IOException ex) {
ex.printStackTrace();
}
}
后台还可以这样简便的写
public String downData(HttpServletRequest request,HttpServletResponse response) throws IOException {
try {
RequestModel requestModel = BaseUtil.getModel(request, response); //自己的一个工具类方法
List
附上service层
// 返回类型 List
public List<Map<String, Object>> queryMember(Map<String, Object> params, Page page) {
StringBuffer sqlBuf = new StringBuffer("SQL语句写在下面");
if (params == null) {
params = new HashMap<String, Object>();
}
if (params.containsKey("memberTel")) {
sqlBuf.append(" and ts.member_tel=:memberTel");
}
if (params.containsKey("memberName")) {
sqlBuf.append(" and tm.member_name like CONCAT('%',:memberName,'%')");
}
return this.customerJPARepository.queryListEntity(sqlBuf.toString(), params); //这个是Dao层自定义查询方法,我定义的是JPA框架中的方法
}
以上sex和birthday直接在写SQL时进行性别判断
//SQL中后面的别名 对应实体类中的属性
SELECT IFNULL(tm.nick_name,'--') nickName,IFNULL(tm.member_name,'--') memberName,IFNULL(tm.merber_tel,'--') merberTel,IFNULL(tm.age,'--') age,
CASE tm.sex WHEN 1 THEN '男' WHEN 0 THEN '女' ELSE '--' END sex,
IFNULL(DATE_FORMAT(tm.birthday,'%Y-%m-%d %T'),'--') merberBirth,IFNULL(tm.member_email,'--') memberEmail
FROM t_member tm
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class ExcelUtil{
/**
* List
public static void exportExcel1(List
maven 中需要加入jar包
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poiartifactId>
<version>3.6version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.47version>
dependency>
其实 对数据的导出,有很多种写法,这是我所用到的一类!