简单粗暴直接贴代码,把所有主要代码全部糅合在一块展示出来:
/**
* 设置导出xls文件的表头
*/
public static final String[] TestToXls = { "变电站","运维班", "记录时间","设备类型", "操作", "设备名称", "记录原因", "用户类型", "授权方式", "用户ID"};
/**
*
*导出数据到excel
* @throws ParseException
*
*/
@RequestMapping("info.do")
public void info(HttpServletRequest request, HttpServletResponse response) throws ParseException{
response.setHeader("Access-Control-Allow-Origin", "*");//解决跨域问题
String filePath ="E:\\excel" + UUID.randomUUID() + "\\";
//加入一个uuid随机数是因为
//每次导出的时候,如果文件存在了,会将其覆盖掉,这里是保存所有的文件
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
// 给要导出的文件起名为 "测试导出数据表_时间.xls"
String filePath2 = filePath + "测试导出数据表" + "_" + fmt.format(new Date()) + ".xls";
WritableWorkbook wb = null;
try {
File file2 = new File(filePath2);
if (!file2.exists()) {//不存在,创建
file2.createNewFile();
}
wb = Workbook.createWorkbook(file2);//创建xls表格文件
// 表头显示
WritableCellFormat wcf = new WritableCellFormat();
wcf.setAlignment(Alignment.CENTRE);// 水平居中
wcf.setWrap(true);
wcf.setVerticalAlignment(VerticalAlignment.CENTRE);// 垂直居中
wcf.setFont(new WritableFont(WritableFont.TIMES,13, WritableFont.BOLD));// 表头字体 加粗 13号
wcf.setBackground(jxl.format.Colour.PERIWINKLE);
// 内容显示
WritableCellFormat wcf2 = new WritableCellFormat();
wcf2.setWrap(true);//设置单元格可以换行
wcf2.setAlignment(Alignment.CENTRE);//水平居中
wcf2.setVerticalAlignment(VerticalAlignment.CENTRE);// 垂直居中
wcf2.setFont( new WritableFont(WritableFont.TIMES,11));// 内容字体 11号
//导出的xls的第一页,第二页就是0换成1,“sheet1”,也可以修改为自己想要的显示的内容
WritableSheet ws = wb.createSheet("sheet1", 0);
//WritableSheet ws2 = wb.createSheet("sheet2", 1);//第2个sheet页
ws.addCell(new Label(0,0, "导出结果"));//代表着表格中第一列的第一行显示查询结果几个字
// 导出时生成表头
for (int i = 0; i < TestToXls.length; i++) {
//i,代表的第几列,1,代表第2行,第三个参数为要显示的内容,第四个参数,为内容格式设置(按照wcf的格式显示)
ws.addCell(new Label(i, 1, TestToXls[i],wcf));//在sheet1中循环加入表头
}
//查询出来的数据,这个方法是演示所用
String sql="com.Test.Service.findAllUser";//sql为mybatis框架下的路径
// Map<String, Object> map = new HashMap<String, Object>();//map里为存放前台的条件
// map.put("prnte", this.getParameter("prnteTest"));
// List<Test> listTest = TestService.findAllList(sql, map);
//获取前台传来的参数进行数据查询
response.setHeader("Access-Control-Allow-Origin", "*");//解决跨域问题
//int rcuid = Integer.parseInt(request.getParameter("rcuid"));
int rcuid = 1049089197;
String bt = null;
String et = null;
String ty = null;
String cc = null;
String vn = null;
String re = null;
String beginTime = request.getParameter("beginTime");//开始时间
if(beginTime == ""||beginTime==null){
bt = null;
}else{
bt = tools.dateToStamp(beginTime);
}
System.out.println("bt:"+bt);
String endTime = request.getParameter("endTime");//结束时间
if(endTime == ""||endTime == null){
et = null;
}else{
et = tools.dateToStamp(endTime);
}
System.out.println("et:"+et);
String itype = request.getParameter("itype");//设备类型
if(itype == ""||itype == null){
ty = null;
}else{
ty = itype;
}
System.out.println("ty:"+ty);
String iControlCode = request.getParameter("iControlCode");//操作
if(iControlCode == ""||iControlCode == null){
cc = null;
}else{
cc = iControlCode;
}
System.out.println("cc:"+cc);
String vcName = request.getParameter("vcName");//设备名称
if(vcName == ""||vcName == null){
vn = null;
}else{
vn = vcName;
}
System.out.println("vn:"+vn);
String iReason = request.getParameter("iReason");//记录原因
if(iReason == ""||iReason ==null){
re = null;
}else{
re = iReason;
}
System.out.println("re:"+re);
List<Integer> aList = cabaService.findAdapterIDByRcuID(rcuid);//根据recuid查询所有adapterID
System.out.println("tiaojianchaxun:"+aList.size());
List<CabHistoryAndDevice> listTest = cabaService.findAllCabInfoByCon(aList,bt,et,ty,cc,vn,re);//按条件查询所有记录
int k =2 ;//从第三行开始写入数据
for (int i = 0; i < listTest.size(); i++) {
ws.addCell(new Label(0, k, "变电站", wcf2));
ws.addCell(new Label(1, k, "运维班",wcf2));
//从list中拿出数据进行处理,直接放到ws中
long time1 = listTest.get(i).getI_time();
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time1 * 1000));//时间
ws.addCell(new Label(2, k, time,wcf2));
//设备类型:0-门 1-机械解锁钥匙 2-电解锁钥匙 3-跳步钥匙 4-电脑钥匙
String dtype = null;
int type = listTest.get(i).getI_Type();
if(type==0){
dtype = "门";
}else if(type==1){
dtype = "机械解锁钥匙";
}else if(type==2){
dtype = "电解锁钥匙";
}else if(type==3){
dtype = "跳步钥匙";
}else if(type==4){
dtype = "电脑钥匙";
}
ws.addCell(new Label(3, k, dtype,wcf2));
//操作码:1取钥匙;2放回钥匙;3开门;4关门;5开机;6关机
String ccode = null;
int code = listTest.get(i).getI_ControlCode();
if(code==1){
ccode = "取钥匙";
}else if(code==2){
ccode = "放回钥匙";
}else if(code==3){
ccode = "开门";
}else if(code==4){
ccode = "关门";
}else if(code==5){
ccode = "开机";
}else if(code==6){
ccode = "关机";
}
ws.addCell(new Label(4, k, ccode,wcf2));
//设备名称
ws.addCell(new Label(5, k, listTest.get(i).getVc_Name(),wcf2));
//记录原因
ws.addCell(new Label(6, k, String.valueOf(listTest.get(i).getI_Reason()),wcf2));
//用户类型:0无效用户 1刷卡用户 2网络用户 3短信用户 4串口用户 5密码用户
String uType = null;
int ut = listTest.get(i).getI_UserType();
if(ut==0){
uType = "无效用户";
}else if(ut==1){
uType = "刷卡用户";
}else if(ut==2){
uType = "网络用户";
}else if(ut==3){
uType = "短信用户";
}else if(ut==4){
uType = "串口用户";
}else if(ut==5){
uType = "密码用户";
}
ws.addCell(new Label(7, k, uType,wcf2));
//授权方式:0网络授权 1密码授权 2刷卡授权 3短信授权 255无授权(在显示记录时以空白表示)
String author = null;
int a = listTest.get(i).getI_Authorization();
if(a==0){
author = "网络授权";
}else if(a==1){
author = "密码授权";
}else if(a==2){
author = "刷卡授权";
}else if(a==3){
author = "短信授权";
}else if(a==255){
author = "无授权";
}
ws.addCell(new Label(8, k, author,wcf2));
ws.addCell(new Label(9, k, String.valueOf(listTest.get(i).getUserID()),wcf2));
//ws.mergeCells(4, 5, 5, 5);//合并两列,按参数顺序,意思是第4列的第五行,跟第五列的第五行合并为一个单元格
k++;
}
wb.write();//写入,到这里已经生成完成,可以在相应目录下找到刚才生成的文件
} catch (IOException e) {
e.printStackTrace();
} catch (JxlWriteException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} finally {
try {
if (wb != null) {
wb.close();
}
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//这个是我们项目中,是把刚才生成的文件,响应到前台,进行下载、保存,可省略。
downLoadFile(filePath2, response);
}
/**
* 下载excel表格
*/
public void downLoadFile(String path, HttpServletResponse response) {
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
我用的是SSM+Maven,jar包地址:<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.10</version>
</dependency>
OK,这样就可以根据前台传来的参数查出相应的数据并导出到excel表格中并下载此表格!!!
参考文章:/zhang_kang_user/article/details/77749449