1、导入jar包
net.sourceforge.jexcelapi
jxl
2.6
2、上代码
protected void exportExcel(HttpServletResponse response, String fileName, String[] Title,
@SuppressWarnings("rawtypes") List content) {
// 以下开始输出到EXCEL
try {
// 定义输出流,以便打开保存对话框______________________begin
OutputStream os = response.getOutputStream();// 取得输出流
response.reset();// 清空输出流
response.setHeader("Content-disposition",
"attachment; filename=" + new String(fileName.getBytes("GB2312"), "ISO8859-1"));
// 设定输出文件头
response.setContentType("application/msexcel");// 定义输出类型
// 定义输出流,以便打开保存对话框_______________________end
/** **********创建工作簿************ */
WritableWorkbook workbook = Workbook.createWorkbook(os);
/** **********创建工作表************ */
WritableSheet sheet = workbook.createSheet("Sheet1", 0);
/** **********设置纵横打印(默认为纵打)、打印纸***************** */
jxl.SheetSettings sheetset = sheet.getSettings();
sheetset.setProtected(false);
/** ************设置单元格字体************** */
WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
/** ************以下设置三种单元格样式,灵活备用************ */
// 用于标题居中
WritableCellFormat wcfCenter = new WritableCellFormat(BoldFont);
wcfCenter.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
wcfCenter.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
wcfCenter.setAlignment(Alignment.CENTRE); // 文字水平对齐
wcfCenter.setWrap(false); // 文字是否换行
// 用于正文居左
WritableCellFormat wcfLeft = new WritableCellFormat(NormalFont);
wcfLeft.setBorder(Border.NONE, BorderLineStyle.THIN); // 线条
wcfLeft.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
wcfLeft.setAlignment(Alignment.LEFT); // 文字水平对齐
wcfLeft.setWrap(false); // 文字是否换行
/** ***************以下是EXCEL第一行列标题********************* */
for (int i = 0; i < Title.length; i++) {
sheet.addCell(new Label(i, 0, Title[i], wcfCenter));
}
/** ***************以下是EXCEL正文数据********************* */
Field[] fields = null;
int i = 1;
for (Object obj : content) {
fields = obj.getClass().getDeclaredFields();
int j = 0;
for (Field v : fields) {
v.setAccessible(true);
Object va = v.get(obj);
if (va == null) {
va = "";
}
sheet.addCell(new Label(j, i, va.toString(), wcfLeft));
j++;
}
i++;
}
workbook.write();
workbook.close();
} catch (Exception e) {
logger.error("export excel failed:" + e.toString());
}
}