/**
* 导出excel文件
* @param sheetName
* @param filename
* @param headlist
* @param datalist
* @return
* @throws Exception
*/
public static byte[] writeExcel(String sheetName, String fileName,
List<String> headlist, List<List> datalist){
if(datalist == null || datalist.size() <= 0){
throw new ETIPException("导出的数据为空");
}
File fileExcel = new File(fileName);
if (!fileExcel.exists()){
try {
fileExcel.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
byte[] data = null;
try {
// 创建一个可写的工作本
WritableWorkbook workbook = Workbook.createWorkbook(fileExcel);
// 创建一个工作单
WritableSheet sheet = workbook.createSheet(sheetName, 0);
// 设置列宽
List objL = (List) datalist.get(0);
int width = objL.size();
for (int i = 0; i < width; i++) {
sheet.setColumnView(i, 15);
}
sheet.mergeCells(0, 0, width - 1, 0);
// 标题样式
WritableFont headerFont = new WritableFont(WritableFont.ARIAL, 10,
WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
jxl.format.Colour.BLACK);
WritableCellFormat headerFormat = new WritableCellFormat(headerFont);
headerFormat.setAlignment(jxl.format.Alignment.CENTRE);
// 数据样式
WritableFont dataFont = new WritableFont(WritableFont.ARIAL, 10,
WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
jxl.format.Colour.BLACK);
WritableCellFormat dataFormat = new WritableCellFormat(dataFont);
dataFormat.setAlignment(jxl.format.Alignment.CENTRE);
// 标题
Label label = new Label(0, 0, fileName, headerFormat);
sheet.addCell(label);
//表头
for (int i = 0; headlist != null && i < headlist.size(); i++) {
String head = (String) headlist.get(i);
label = new Label(i, 1, head, headerFormat);
sheet.addCell(label);
}
// 动态填充数据
for (int i = 0; datalist != null && i < datalist.size(); i++) {
List recordfield = (List) datalist.get(i);
for (int j = 0; j < recordfield.size(); j++) {
label = new Label(j, i + 2, String.valueOf(recordfield.get(j)),
dataFormat);
sheet.addCell(label);
}
}
workbook.write();
workbook.close();
//file转换 byte
FileInputStream hFile = new FileInputStream(fileExcel);
data = new byte[hFile.available()];
hFile.read(data);
hFile.close();
} catch (RowsExceededException e) {
} catch (WriteException e) {
} catch (IOException e) {
}
return data;
}
action 类 方法里面
try {
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment; filename=BankBasicInfo("+format1.format(new Date())+").xls");
byte[] data1 = ExcelHandle.writeExcelBank("银行整体信息", "银行整体信息", hendList, dataList,whichList);
response.getOutputStream().write(data1);
response.getOutputStream().flush();
} catch (Exception e) {
e.printStackTrace();
}
上面的那方法适合固定的集合 会把集合里面的对象每一个字段都填充到execl
下面的方法适合任意对象,制定需要填充的字段
/**
* 生成Execl
*
* @param list
* 对象集合
* @param title
* execl 标题
* @param headers
* 键值对 LinkedHashMap 保证顺序 key String value String 键 表示需要写入Execl
* 对象指定的字段 值必须为对象属性(不区分大小写) 值 表示写入Execl 对象字段的中文标题 如 Student name
* --> 姓名
* @param fileName
* 生成execl 的文件名
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void writeExecl(List list, String title,
LinkedHashMap headers, String fileName) {
try {
OutputStream os = ServletActionContext.getResponse().getOutputStream();
ServletActionContext.getResponse().setHeader("Content-disposition","attachment; filename=" + new String(fileName.getBytes("GBK"), "iso-8859-1") + ".xls");
ServletActionContext.getResponse().setContentType("application/msexcel");
//
WritableWorkbook book = Workbook.createWorkbook(os);
// 生成名为“title”的工作表,参数0表示这是第一页
WritableSheet sheet = book.createSheet(title, 0);
WritableCellFormat bigGreyBackground = setFmt(); // 大标题样式
WritableCellFormat contentStyle = setlable(); // 内容样式
WritableCellFormat smallBackground = setTHd();
// 大标题
Label label = new Label(0, 0, title, bigGreyBackground);
sheet.addCell(label);
Iterator it = headers.entrySet().iterator();
// 小标题
int headColum = 0;
while (it.hasNext()) { // 添加表头
Entry entry = (Entry) it.next();
sheet.setColumnView(headColum, 19); // 设置列的宽度
addSheet(sheet,entry.getValue(),smallBackground,label,headColum,1);
headColum++;
}
/*
* 合并单元格 通过writablesheet.mergeCells(int x,int y,int m,int n);来实现的
* 表示将从第x+1列,y+1行到m+1列,n+1行合并
*/
sheet.mergeCells(0, 0, headColum - 1, 0); // 合并单元格 标题
for (int i = 0; i < list.size(); i++) {// 添加内容
sheet.setRowView(i +3, 800); // 设置行的高度
Object obj = list.get(i);
// Field [] fields = obj.getClass().getDeclaredFields();
// //得到对象的属性
Method[] methods = obj.getClass().getDeclaredMethods(); // 得到对象的所有方法
Iterator its = headers.entrySet().iterator();
int contentCol = 0;
while (its.hasNext()) {
Entry entry = (Entry) its.next();
String key = entry.getKey() + ""; // 返回与此项对应的键
for (int j = 0; j < methods.length; j++) {
Method method = methods[j]; // 得到单个方法
String methodName = method.getName().toString();
boolean isGet = methodName.substring(0, 3).equals("get"); // 得到此方法是get打头
String methodNamekey = methodName.substring(3,methodName.length());
// 不区分大小写的比较值 如果返回true 代表此属性需要写入Exelc
if (isGet && methodNamekey.equalsIgnoreCase(key)) {
Object value = method.invoke(obj, new Object[] {}); // 执行方法,得到值
// 添加到工作表
addSheet(sheet,value,contentStyle,label,contentCol,i + 2);
break;
}
}
contentCol++;
}
}
// 写入数据并关闭文件
book.write();
os.flush();
book.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 添加数据到sheet
* @param sheet 当前sheet
* @param value 值
* @param fmt 格式化
* @param label 当前label
* @param contentCol 列
* @param row 行
* @throws Exception
*/
public static void addSheet(WritableSheet sheet,Object value,WritableCellFormat fmt,Label label,
int contentCol,int row) throws Exception{
String textValue="";
if (value != null) {
if (value instanceof Date) { // 如果这个值为时间
// DateFormat df = new DateFormat("yyyy-MM-dd");
// WritableCellFormat wcfDF = new WritableCellFormat(df);
// DateTime labelDTF = new DateTime(contentCol, row, (Date) value, wcfDF);
label = new Label(contentCol, row,new SimpleDateFormat("yyyy-MM-dd").format(value), fmt);
sheet.addCell(label);
} else { // 其余的都当做字符串 如果有具体的业务还需要具体实现
textValue = value.toString();
label = new Label(contentCol, row, textValue, fmt);
sheet.addCell(label);
}
}else{
label = new Label(contentCol, row, textValue, fmt);
sheet.addCell(label);
}
}
public static String getRealPath() {
return ServletActionContext.getServletContext().getRealPath("/");
}
private static boolean isEntity(String fullName) {
String[] packs = fullName.split(" ");
if (packs[2].startsWith(packs[1].substring(0, packs[1].lastIndexOf(".")))) {
return true;
}
return false;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void writeInExcel(List list_data, String[] columnNames,
String filePath) {
try {
WritableWorkbook book = Workbook.createWorkbook(new File(filePath));
WritableSheet sheet = book.createSheet("第一页", 0);
Label lab = null;
for (int i = 0; i < (columnNames == null ? 0 : columnNames.length); i++) {
lab = new Label(i, 0, columnNames[i]);
sheet.addCell(lab);
}
for (int j = 0; j < list_data.size(); j++) {
Field[] fids = list_data.get(j).getClass().getDeclaredFields();
for (int i = 0; i < fids.length; i++) {
fids[i].setAccessible(true);
Object tempObj = fids[i].get(list_data.get(j)); // fids[i].get
//if (isEntity(fids[i].toString()) && tempObj != null)
// continue;
if (tempObj == null)
tempObj = "";
lab = new Label(i, j + 1, tempObj + "");
sheet.addCell(lab);
fids[i].setAccessible(false);
}
}
book.write();
book.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 设置标题的样式
*
* @return
*/
public static WritableCellFormat setFmt() throws Exception {
WritableFont bigTitleFont = new WritableFont(WritableFont.ARIAL, 16,
WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE);
WritableCellFormat bigGreyBackground = new WritableCellFormat(bigTitleFont);
bigGreyBackground.setWrap(false);
bigGreyBackground.setVerticalAlignment(VerticalAlignment.CENTRE);
bigGreyBackground.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
bigGreyBackground.setAlignment(Alignment.CENTRE);
return bigGreyBackground;
}
/**
* 设置内容的样式
*
* @return
*/
public static WritableCellFormat setlable() throws Exception {
WritableFont wfc = new WritableFont(WritableFont.ARIAL, 11, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE);
WritableCellFormat wcfFC = new WritableCellFormat(wfc);
wcfFC.setBackground(Colour.WHITE);// 设置单元格的颜色为白色色
wcfFC.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
wcfFC.setAlignment(Alignment.CENTRE);
return wcfFC;
}
/**
* 设置表头样式
*
* @return
*/
public static WritableCellFormat setTHd() throws Exception {
WritableFont smallBackground = new WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE);
WritableCellFormat wcfFC = new WritableCellFormat(smallBackground);
wcfFC.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
wcfFC.setAlignment(Alignment.CENTRE);
return wcfFC;
}
在action类里面
// @SuppressWarnings({ "rawtypes", "unchecked" })
// public void getExpView(){
// String ids = request.getParameter("ids");
// String falg= request.getParameter("falg");
// List<ETIPResultSet> ls = proRelatUserFacade.getExpproList(ids,falg);
//
// List list =null;
// if(ls!=null && ls.size()>0){
// list = new ArrayList();
// //ETIPResultSet emap = null;
// for(int i=0;i<ls.size();i++){
// SysProjectData sdata=new SysProjectData();
// ETIPResultSet emap = (ETIPResultSet)ls.get(i);
// String id = (String)emap.getString("ID");
// String applyCode = (String)emap.getString("APPLYCODE");
// String projectCode=(String)emap.getString("PROJECTCODE");
// String projectName=(String)emap.getString("PROJECTNAME");
// String zrole1Name=(String)emap.getString("ZROLENO1NAME");
// Date createDateTime = (Date)emap.getDate("CREATEDATETIME");
// sdata.setApplyCode(applyCode);
// sdata.setProjectCode(projectCode);
// sdata.setProjectName(projectName);
// sdata.setZrole1Name(zrole1Name);
// sdata.setCreateDateTime(createDateTime);
// sdata.setId(id);
// list.add(sdata);
// }
// }
//
// String title = "项目信息" ; //标题
// LinkedHashMap headers =new LinkedHashMap<String, String>(); //表头
// headers.put("APPLYCODE", "申请编号");
// headers.put("PROJECTCODE", "项目编号");
// headers.put("PROJECTNAME", "项目名称");
// headers.put("ZROLE1NAME", "第一责任人");
// headers.put("CREATEDATETIME", "创建时间");
//
// String fileName = "项目信息报表";
// ExcelUtil.writeExecl(list, title, headers, fileName); //生成
// //String columnNames[]={"申请编号","项目编号","项目名称","第一责任人","创建时间"};
// //ExcelUtil.writeInExcel(list, columnNames, "d:\\test.xls");
// }