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);
}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章