public String exportExcel() throws Exception {
HttpServletRequest request=ServletActionContext.getRequest();
HttpServletResponse response=ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("file");
try {
response.setHeader("Content-Disposition", "inline; filename="+ new String("使用EXCEL.xls".getBytes("GB2312"), "iso8859-1"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 这个地方一定要进行编码的转换要不然中文字符会出现乱码.
// 设置下载头信息.end,
OutputStream output = null;
InputStream fis = null;
try {
output = response.getOutputStream();
jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(output);
jxl.write.WritableFont wf = new jxl.write.WritableFont(WritableFont.TIMES, 18, WritableFont.BOLD, true);
jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat(wf);
wcfF.setWrap(true);//自动换行
wcfF.setAlignment(jxl.format.Alignment.CENTRE);//把水平对齐方式指定为居中
wcfF.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
jxl.write.WritableSheet sheet = wwb.createSheet("使用EXCEL", 0);
CellView cv = new CellView(); //定义一个列显示样式
cv.setFormat(wcfF);//把定义的单元格格式初始化进去
cv.setSize(30*200);//设置列宽度(不设置的话是0,不会显示)
sheet.mergeCells(0,0,4,0); //合并单元格
sheet.setColumnView(0, cv);//设置工作表中第n列的样式
sheet.addCell(new Label(0, 0, "使用EXCEL",wcfF));
NumberFormat dp3 = new NumberFormat("###,###"); //设置单元格里面的数字格式
WritableCellFormat dp3cell = new WritableCellFormat(dp3);
dp3cell.setWrap(true);
Number number = new Number(1,1,1,dp3cell);
sheet.addCell(number);
number = new Number(1,2,1,dp3cell);
sheet.addCell(number);
Formula f = new Formula(1, 3, "SUM(B2:B3)", dp3cell); //设置C10公式
sheet.addCell(f);
wwb.write();
wwb.close();
} catch (Exception e) {
System.out.println("Error!");
e.printStackTrace();
} finally {// 正常关闭输入输出流.
try {
if (fis != null) {
fis.close();
fis = null;
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (output != null) {
output.close();
output = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}