Strus2 导出excel模板
因为每个公司的返回值不一样,在网上找到很多的返回SUCCESS的,但是到我这里直接跳转到空白页面出现json。
话不多说,上代码
首先Strus。xml不需要咋配置
正常写就可以;
action就这样写:
private String fileName;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
// 下载文件的文件名
public String exportCldj() {
// rows = fflService.queryByFfl(qsrq, jsrq, ssjdm);
fileName = this.createExcelFile(null, MyUtil.toUTF8String("模板"));
return AJAX;
}
public String createExcelFile(List list, String leftFilename) {
String rootpath = ServletActionContext.getRequest().getRealPath("/") + "/upload/"; // 路径
String filename = leftFilename + "_" + PubMethod.dateToString(new Date(), "yyyyMMdd_HHmmss") + ".xls";// 文件名
this.writeExcelBT(rootpath, filename, null);
return filename;
}
public static void writeExcelBT(String path, String filename, List list) {
OutputStream os = null;
try {
os = new FileOutputStream(path + filename);
} catch (FileNotFoundException e1) {
File file = new File(path);
if (!file.exists()) {// 判断文件夹是否存在
file.mkdir();
}
try {
os = new FileOutputStream(path + filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
try {
// 打开文件
WritableWorkbook book = jxl.Workbook.createWorkbook(os);
// 生成名为“第一页”的工作表,参数0表示这是第一页
WritableSheet sheet = book.createSheet(" 第一页 ", 0);
SheetSettings ss = sheet.getSettings();
// ss.setHorizontalFreeze(2); // 设置列冻结
ss.setVerticalFreeze(4); // 设置行冻结前2行
WritableFont font1 = new WritableFont(WritableFont.createFont("微软雅黑"), 10, WritableFont.BOLD);
WritableFont font2 = new WritableFont(WritableFont.createFont("微软雅黑"), 9, WritableFont.NO_BOLD);
WritableFont font3 = new WritableFont(WritableFont.createFont("微软雅黑"), 9, WritableFont.BOLD);
WritableCellFormat wcf = new WritableCellFormat(font1);
WritableCellFormat wcf2 = new WritableCellFormat(font2);
WritableCellFormat wcf3 = new WritableCellFormat(font2);// 设置样式,字体
WritableCellFormat wcf4 = new WritableCellFormat(font3);// 设置样式,字体
wcf4.setBackground(Colour.RED);
wcf.setAlignment(Alignment.CENTRE); // 平行居中
wcf.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直居中
wcf3.setAlignment(Alignment.CENTRE); // 平行居中
wcf3.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直居中
wcf3.setBackground(Colour.LIGHT_ORANGE);
wcf2.setAlignment(Alignment.CENTRE); // 平行居中
wcf2.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直居中
wcf4.setAlignment(Alignment.CENTRE); // 平行居中
wcf4.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直居中
sheet.mergeCells(0, 0, 16, 0); // 合并单元格 第三个参数 = 表头的列数-1
// String[] groupNames = new String[1]; groupNames[0] = "rq";
// RowTabManager rowTabMange = new RowTabManager(list, groupNames);
// List<RowTabItem> row = rowTabMange.rowTableItemList;
Label titleLabel = new Label(0, 0, "系统-路单查询", wcf);
// 将定义好的单元格添加到工作表中
sheet.addCell(titleLabel);
sheet.mergeCells(0, 1, 16, 1);
Label titleLabel2 = new Label(0, 1, "备注:*********************************",
wcf4);
sheet.addCell(titleLabel2);
sheet.setRowView(1, 400);
sheet.setRowView(2, 410); // 设置第一行的高度 20121111
sheet.setRowView(3, 450);
// int[] headerArrHight = {20,20,20}; //表头宽度
int gudingHeight = 20;
String headerArr0[] = new String[] { "例:*","*1)","*9","赣AF0568","*挂","G","0","101","4","5","59","8.068","100.00","未进局","2020-11-03 04:23","11","2"};
for (int i = 0; i < headerArr0.length; i++) {
sheet.addCell(new Label(i, 2, headerArr0[i], wcf));
sheet.setColumnView(i, gudingHeight);
}
String headerArr[] = new String[] { "型", "对象", "单号", "航班|车牌号", "车厢|车牌号", "车厢码", "封车码", "流水号", "总数",
"袋", "件", "重量(kg)", "率", "状态", "时间", "类型", "目的地" };
for (int i = 0; i < headerArr.length; i++) {
sheet.addCell(new Label(i, 3, headerArr[i], wcf3));
sheet.setColumnView(i, gudingHeight);
}
// SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
/*
* int count = 2; for(int i=0;i<list.size();i++){ //表头从0开始 sheet.addCell(new
* Label( 0 , count ,list.get(i).getYjzl(),wcf2)); sheet.addCell(new Label( 1 ,
* count ,list.get(i).getZbsl()+"",wcf2)); sheet.addCell(new Label( 2 , count
* ,list.get(i).getSjsl()+"",wcf2)); sheet.setRowView(count, 370); // 设置第一行的高度
* count++; }
*/
// 写入数据并关闭文件
book.write();
book.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String download() throws UnsupportedEncodingException {
HttpServletRequest request = ServletActionContext.getRequest();
String url = request.getRealPath("/upload") + File.separator + fileName;
HttpServletResponse response = ServletActionContext.getResponse();
System.out.println(url);
File file = new File(url);
response.reset();
response.setContentType("");// 设置下载文件的类型
response.setHeader("content-disposition", "attachment; filename=" + new String(fileName)); // 设置下载的文件名
long fileLength = file.length();
String length1 = String.valueOf(fileLength);
response.setHeader("Content_Length", length1); // 下载文件的大小
InputStream in = null;
OutputStream out = null;
try {
out = response.getOutputStream();
in = new FileInputStream(file);
byte[] buffer = new byte[2097152];
int ins = in.read(buffer);// 读取字节到buffer中
// ins == -1 时 。就已经是文件的结尾了
while (ins != -1) {
out.write(buffer, 0, ins);// 将缓存buffer中的数据写到文件中
ins = in.read(buffer);
}
} catch (Exception e) {
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.flush();
}
if (out != null) {
out.close();
}
} catch (IOException e1) {
System.out.println("--关闭发生异常--");
in = null;
out = null;
e1.printStackTrace();
}
}
return null;
}
然后是jsp界面;
<td>
<a href="javascript:void(0);" class="easyui-linkbutton"
data-options="iconCls:'icon-ok',plain:true"
onclick="exportExcel();">导出EXCEL模板</a></td>
<td>
<div id="fflDownloadDialog"/>
//导出EXCEL
function exportExcel() {
$.ajax( {
type : "post",
url : "${ctx}/cldj/cldj_exportCldj.action",
cache : false,
dataType:"json",
success : function(json) {
var fileName = encodeURI(json["fileName"]);
var url = "${ctx}/cldj/cldj_download.action?fileName="+fileName;
showDownloadDialog(fileName,url);
},
complete : function(XMLHttpRequest, textStatus) {
},
error : function(msg) {
$.messager.alert('操作提示', msg, 'error');
}
});
}
//显示下载按钮
function showDownloadDialog(fileName,url) {
var htmlstr = '<table align="center" width="100%" height="100%">';
htmlstr += '<tr align="center">';
htmlstr += '<td align="center">';
htmlstr += '<a href="'+url+'" id="down" ><font size="3" color="blue">下载</font></a>';
htmlstr += '</td>';
htmlstr += '</tr>';
htmlstr += '</table>';
using( [ 'dialog' ], function() {
$('#fflDownloadDialog').dialog( {
title : '车辆登记',
width : 200,
height : 90,
top : 150,
content : htmlstr
});
});
}
还有就是解决文件名乱码的问题;这里用到一个myutil
package dvt.util.file;
import java.io.UnsupportedEncodingException;
public class MyUtil {
// 对下载文件按照 UTF-8 进行编码
public static String toUTF8String(String str){
StringBuffer sb = new StringBuffer();
int len = str.length();
for (int i = 0; i < len; i++)
{
// 取出字符中的每个字符
char c = str.charAt(i);
// Unicode码值在0~255之间,不做处理
if(c>=0 && c <= 255){
sb.append(c);
}else {
// 转换 UTF-8 编码
byte b[];
try{
b = Character.toString(c).getBytes("UTF-8");
}catch(UnsupportedEncodingException e){
e.printStackTrace();
b = null;
}
// 转换为%HH的字符串形式
for(int j = 0;j < b.length ; j++){
int k = b[j];
if(k < 0){
k &= 255;
}
sb.append("%" + Integer.toHexString(k).toUpperCase());
}
}
}
return sb.toString();
}
}