jxl 写 excle 文件并下载

action 中代码:

// 文件名
String fileName = glRoadPart.getPartName()+"【"+pdMaintenanceQuality.getStartNum()+"—"+pdMaintenanceQuality.getEndNum()+"】"+pdMaintenanceQuality.getAssessMan()+DateUtil.convertDateToString(pdMaintenanceQuality.getAssessDate())+System.currentTimeMillis()+".xls";
// 目录
String directory = this.servlet.getServletContext().getRealPath("temp");
if (!FileUtil.isDirectoryExist(directory)) {
FileUtil.createDirectory(directory);
}
//新建Excel文件
String filePath = directory+"/"+fileName;
File excleFile=new File(filePath);
if (!excleFile.exists()) {
excleFile.createNewFile();
}
OutputStream outf = new FileOutputStream(excleFile);
WritableWorkbook workbook = Workbook.createWorkbook(outf);
AssessmentExportExcelUtil.getInstance().exportAll(workbook, pdMaintenanceQuality, glRoadSurfaceInfo, glRoadPart, this.servlet.getServletContext());
workbook.write();
workbook.close(); //一定要关闭, 否则没有保存Excel
outf.close();
// 设置响应类型和响应首部
response.setContentType("application/vnd.ms-excel");
// UploadFile.downloadFile(request, response, excleFile);
UploadFile.downloadFileByInputStream(request, response, excleFile);
//删除文件
FileUtil.deleteFile(excleFile);


下载代码:

/**
* 下载文件
* @param request
* @param response
* @param file
* @return
* @throws IOException
*/
public static boolean downloadFileByInputStream(HttpServletRequest request, HttpServletResponse response, File file) throws IOException {
if (file!=null) {
InputStream fileInput = null;
OutputStream filetoClient = null;
try {
fileInput = new FileInputStream(file);
filetoClient = response.getOutputStream();
byte[] buffer = new byte[1024*8];
int len=0;
// 写入输出流
while((len = fileInput.read(buffer)) != -1){
filetoClient.write(buffer, 0, len);
}
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(file.getName(), "UTF-8") + "\"");
} catch (IOException e) {
log.error("can not download", e);
e.printStackTrace();
response.sendError(405, "File cannot found!");
return false;
} finally {
try {
if (fileInput != null) {
fileInput.close();
}
fileInput = null;

if (filetoClient != null) {
filetoClient.flush();
filetoClient.close();
}
filetoClient =null;
} catch (IOException e) {
log.error("can not download", e);
e.printStackTrace();
response.sendError(405, "download error!");
return false;
}
}
return true;
} else {
log.error(" file is null");
response.sendError(405, "File cannot found!");
return false;
}
}


注:下载文件试过用 Writer 和 Reader 实现,但下载下来的文件有文件,不知是不是 Struts 的 writer 实现不同

写 excel 帮助类(懒得整理了,整个代码弄上来吧)


import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.xx.xx.yy.model.GlRoadPart;
import com.xx.xx.yy.model.GlRoadSurfaceInfo;
import com.xx.xx.xx.model.PdAssessItem;
import com.xx.xx.xx.model.PdMaintenanceQuality;
import com.xx.xx.xx.vo.ColumnVo;
import com.xx.xx.system.service.AppCodeManager;
import com.xx.xx.system.util.DateUtil;

public final class AssessmentExportExcelUtil {
private static AssessmentExportExcelUtil instance;
/** 私有构造方法,以防外部类 new 出实例 */
private AssessmentExportExcelUtil(){}
public static synchronized AssessmentExportExcelUtil getInstance() {
if (instance==null) {
instance = new AssessmentExportExcelUtil();
}
return instance;
}
public synchronized void exportAll(WritableWorkbook workbook, PdMaintenanceQuality pdMaintenanceQuality, GlRoadSurfaceInfo glRoadSurfaceInfo, GlRoadPart glRoadPart, ServletContext servletContext) throws InterruptedException {
GlRoadSurfaceInfo glRoadSurfaceInfo, GlRoadPart glRoadPart, ServletContext servletContext) {
List<PdAssessItem> pdAssessItems = AssessmentUtil.getInstance().getPdAssessItems(pdMaintenanceQuality, this.EQUIPMENT_CODE);
AppCodeManager appCodeManager = (AppCodeManager) getBean("appCodeManager", servletContext);
String direction = appCodeManager.getAppCodesByCategory(216, pdMaintenanceQuality.getDirection()).getCodeName();
List<ColumnVo> columnVos= this.getSurveryTypeContents(this.EQUIPMENT_CODE);
String sheetName = "sheet 1";
WritableSheet sheet = workbook.createSheet(sheetName, 4);
WritableFont wf = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false);//设置写入字体
try {
// title 单元格样式,加粗居中
WritableCellFormat centerBoldFormat = new WritableCellFormat(wf);
// 设置细边框
centerBoldFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
// 单元格居中对齐
centerBoldFormat.setAlignment(Alignment.CENTRE);
centerBoldFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
centerBoldFormat.setWrap(true);
// title 单元格样式,加粗靠左对齐
WritableCellFormat leftBoldFormat = new WritableCellFormat(wf);
// 设置细边框
leftBoldFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
// 单元格靠左对齐
leftBoldFormat.setAlignment(Alignment.LEFT);
// 正文字样式
WritableCellFormat normalFormat = new WritableCellFormat();
normalFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
normalFormat.setAlignment(Alignment.CENTRE);
normalFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
// 标题样式
WritableCellFormat titleFormat = new WritableCellFormat(wf);
titleFormat.setAlignment(Alignment.CENTRE);
titleFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
int r = 0;
// 写 title
sheet.addCell(new Label(0, r++, sheetName+"损坏调查表", titleFormat));
// 合并第 0 行至第一行的1至16单元格
sheet.mergeCells(0, 0, 15, r++);
// 写表头
WritableCell labelCF = new Label(0, r, " 路线名称:"+glRoadPart.getPartName(), leftBoldFormat);
sheet.addCell(labelCF);
sheet.setColumnView(0, 25);
labelCF = new Label(1, r, " 调查方向:"+direction, leftBoldFormat);
sheet.addCell(labelCF);
// 合并2~5单元格
sheet.mergeCells(1, r, 4, r);
labelCF = new Label(5, r, " 调查时间:"+DateUtil.convertDateToString(pdMaintenanceQuality.getAssessDate())+" 调查人员:"+pdMaintenanceQuality.getAssessMan(), centerBoldFormat);
sheet.addCell(labelCF);
// 合并5~15单元格
sheet.mergeCells(5, r, 15, r++);
labelCF = new Label(0, r, "调查内容", centerBoldFormat);
sheet.addCell(labelCF);
// 合并1~3行
sheet.mergeCells(0, r, 0, r+2);
// 设置单元格宽度
for (int i = 1; i < 16; i++) {
sheet.setColumnView(i, 5);
}
labelCF = new Label(1, r, "程度", centerBoldFormat);
sheet.addCell(labelCF);
sheet.mergeCells(1, r, 1, r+2);
labelCF = new Label(2, r, "单位扣分", centerBoldFormat);
sheet.addCell(labelCF);
sheet.mergeCells(2, r, 2, r+2);
labelCF = new Label(3, r, "权重Wi", centerBoldFormat);
sheet.addCell(labelCF);
sheet.mergeCells(3, r, 3, r+2);
labelCF = new Label(4, r, "计量单位", centerBoldFormat);
sheet.addCell(labelCF);
sheet.mergeCells(4, r, 4, r+2);
// 设为无下边框
WritableCellFormat tempFormat1 = new WritableCellFormat(wf);
tempFormat1.setBorder(Border.TOP, BorderLineStyle.THIN);
tempFormat1.setBorder(Border.LEFT, BorderLineStyle.THIN);
tempFormat1.setBorder(Border.RIGHT, BorderLineStyle.THIN);
tempFormat1.setAlignment(Alignment.CENTRE);
labelCF = new Label(5, r, "起点桩号:"+pdMaintenanceQuality.getStartNum()+" 终点桩号:"+pdMaintenanceQuality.getEndNum(), tempFormat1);
sheet.addCell(labelCF);
sheet.mergeCells(5, r, 14, r);
labelCF = new Label(15, r, "累计损坏", centerBoldFormat);
sheet.addCell(labelCF);
sheet.mergeCells(15, r, 15, r+2);
r++;
// 设为无下边框
WritableCellFormat tempFormat2 = new WritableCellFormat(wf);
tempFormat2.setBorder(Border.BOTTOM, BorderLineStyle.THIN);
tempFormat2.setBorder(Border.LEFT, BorderLineStyle.THIN);
tempFormat2.setBorder(Border.RIGHT, BorderLineStyle.THIN);
tempFormat2.setAlignment(Alignment.CENTRE);
labelCF = new Label(5, r, "路段长度:"+pdMaintenanceQuality.getRoadLength()+" 路面宽度:"+glRoadSurfaceInfo.getRoadSurfaceWidth(), tempFormat2);
sheet.addCell(labelCF);
sheet.mergeCells(5, r, 14, r++);
for (int i = 1; i < 11; i++) {
labelCF = new Label(4+i, r, i+"", centerBoldFormat);
sheet.addCell(labelCF);
}
r++;
int count = columnVos.size();
// 写表格体
for (int i=0;i<count;i++) {
int start = r;
ColumnVo col = (ColumnVo)columnVos.get(i);
String unit = col.getUnit();
// 替换平方米
if (unit != null && unit.endsWith("</sup>")) {
unit = "㎡";
}
// 程度
List<String> scopes = col.getScope();
// 程度代码
List<String> scopeCodes = col.getScopeCode();
// 单位扣分
List<String> dedUcts = col.getDeduct();
// 权重
List<String> powers = col.getPower();
int size = dedUcts.size();
// 调查内容
labelCF = new Label(0, start, col.getContent(), normalFormat);
sheet.addCell(labelCF);
// 权重
labelCF = new Label(3, start, powers.get(0), normalFormat);
sheet.addCell(labelCF);
// 计量单位
labelCF = new Label(4, start, unit, normalFormat);
sheet.addCell(labelCF);
int end = start + size -1;
if (size>1) {
sheet.mergeCells(0, start, 0, end);
sheet.mergeCells(3, start, 3, end);
sheet.mergeCells(4, start, 4, end);
r = end;
}
for (int j = 0; j < size; j++) {
String scope = scopeCodes.get(j);
List<PdAssessItem> items = this.filterPdAssessItems(pdAssessItems, col.getContentCode(), scope);
labelCF = new Label(1, start+j, scopes.get(j), normalFormat);
sheet.addCell(labelCF);
labelCF = new Label(2, start+j, dedUcts.get(j), normalFormat);
sheet.addCell(labelCF);
Double total = new Double("0");
// 十个调查格
for (int k = 1; k <= 11; k++) {
if (k==11) {
labelCF = new Label(4+k, start+j, this.formatNumber(total), normalFormat);
sheet.addCell(labelCF);

} else {
Double value = this.getValue(items, k);
String valueStr = "";
if (value != null){
total += value;
valueStr = value.toString();
}
labelCF = new Label(4+k, start+j, valueStr, normalFormat);
sheet.addCell(labelCF);
}
}
}
r++;
}
} catch (WriteException e) {
e.printStackTrace();
}
}


/**
* 根据 bean 名称从指定的 servletContext 获取实例
* @param name
* @param servletContext
* @return
*/
private Object getBean(String name, ServletContext servletContext) {
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
return ctx.getBean(name);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值