首先,(需要导入jxl.jar)建立一个辅助类JXLUtil,类里封装好Excel的格式以及参数等:
JXLUtil类:
public class JXLUtil {
/****
* @author :QZC
* @createDate :2015年7月24日 下午14:29:47
**Description :根据格式索引返回单元格的格式
* @param formatIndex
* @return
****
*/
public static WritableCellFormat FetchColFormat(Integer formatIndex){
WritableCellFormat cellFormat=new WritableCellFormat(NumberFormats.DEFAULT);
try{
switch(formatIndex){
case 0://文本型
cellFormat=new WritableCellFormat(NumberFormats.TEXT);
break;
case 1://整型
cellFormat=new WritableCellFormat(NumberFormats.INTEGER);
break;
case 2://浮点型
cellFormat=new WritableCellFormat(NumberFormats.FLOAT);
break;
default:
}
}catch(Exception e){
e.printStackTrace();
}
return cellFormat;
}
/******
* @author :QZC
* @createDate :2015年7月24日 下午15:11:25
* 函数功能描述:输出
* @param response
* @param templateName 输出模板名称
* @param title Excel表头,格式如:{"库位编号|20|0","货位编号|20|0"};
****
*/
public static void OutExcelTemplate(HttpServletResponse response,
String templateName,
String title[]){
WritableWorkbook workbook = null;
try {
try{
OutputStream outPutS = response.getOutputStream();
response.resetBuffer();
String outFileName=new String(templateName.getBytes("gb2312"),"ISO8859-1") + ".xls";
response.setHeader("Content-disposition","attachment;filename="+outFileName);
response.setContentType("application/excel");
workbook = Workbook.createWorkbook(outPutS);
WritableSheet sheet = workbook.createSheet("sheet1", 0);
Label label = null;
/** 字体设置 */
WritableFont headerFont = new WritableFont(WritableFont.ARIAL, 12,
WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
Colour.BLACK);
/** 格式 */
WritableCellFormat headerFormat = new WritableCellFormat(headerFont);
headerFormat.setAlignment(Alignment.LEFT);
headerFormat.setWrap(true);
WritableFont titleFont = new WritableFont(WritableFont.ARIAL, 12,
WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
Colour.BLACK);
WritableCellFormat titleFormat = new WritableCellFormat(titleFont);
titleFormat.setAlignment(Alignment.CENTRE);
int col = 0;
for (int i = 0; i < title.length; i++) {
String[] arrayTitle = title[i].split("\\|");
label = new Label(col, 0, arrayTitle[0],titleFormat);
sheet.addCell(label);
// 设置列宽
sheet.setColumnView(col, Integer.parseInt(arrayTitle[1]),JXLUtil.FetchColFormat(Integer.parseInt(arrayTitle[2])));
col++;
}
workbook.write();
workbook.close();
}catch(Exception e1){
if(workbook!=null){
workbook.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
模版辅助类封装好后,调用:
public void downloadContractModel(HttpServletResponse response) {
String outFileName = "合同折扣明细模版";
String title[] = { "物料号|20|0", "物料描述|40|0", "单位|30|0", "上年度价格|30|0","本年度价格|20|0", "折扣|20|0", "品牌|20|0" };
JXLUtil.OutExcelTemplate(response, outFileName, title);
}