package com.chinalife.contract.common.util;
import java.util.List;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.annotations.Entity;
//import org.jfree.util.Log;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class ExportExcel {
Log log4j;
/**
* 将列表导出Excel
*
* @param condition 查询条件 (非必需)
* @param title 标题 (非必需)
* @param columnName 列名 (非必需)
* @param list 查询结果 (非必需)
* @param request (必需)
* @param response (必需)
* @throws Exception
*
* */
public void exportExcel(String title, String condition, String columnName,
List list, HttpServletRequest request, HttpServletResponse response) {
// 查询条件 (注意:就算condition为空,split过后condition的length为1,也就影响notCondition值)
try {
// 所有传递参数为空也能生成excel
if (condition != null) {
} else {
condition = "";
}
if (columnName != null) {
} else {
columnName = "";
}
if (title != null) {
} else {
title = "";
}
if (list != null) {
} else {
list = new ArrayList();
}
String conditions[] = condition.split(",");
// 列名称数组,数组长度为列数
String columnNames[] = columnName.split(",");
// excel在服务器中所在路径
String unloadPath = getWebRootPath(request) + "\\download\\"
+ "excel" + "\\";
// 定义一个book对象
WritableWorkbook book = null;
// 自动生成日期
SimpleDateFormat autoDate = new SimpleDateFormat(
"yyyyMMddHHmmssSSS");
// excel名为:当前名+日期时间
title = title + autoDate.format(new Date());
File dirFile = new File(unloadPath);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
dirFile.mkdirs();
}
// 创建excel文件
book = Workbook
.createWorkbook(new File(unloadPath + title + ".xls"));
// 生成名为“第一页”的工作表,参数0表示这是第一页
WritableSheet sheet = book.createSheet("第一页", 0);
Label label = new Label(columnNames.length / 2, 0, title);
// 1插入标题信息(占用第1行)
sheet.addCell(label);
// 没有查询条件,从标题下一行插入列表的计数器
int notCondition = 0;
// 2插入查询条件(从第2到1+conditions.length行)
if (condition.length() > 0)// 没有查询条件
{
for (int i = 0; i < conditions.length; i++) {
String param = conditions[i].substring(0,
conditions[i].indexOf("="));// 截取"="前面的
String value = conditions[i].substring(
conditions[i].indexOf("=") + 1,
conditions[i].length());// 截取"="后面的
label = new Label(0, i + 1, param);
sheet.addCell(label);
if (value != null && !value.equals("")
&& !value.equals("null")) {
label = new Label(1, i + 1, value);// 截取"="后面的
sheet.addCell(label);
}
}
} else {
notCondition = 2;
}
// 3插入列标题(占用第2+conditions.length行,与查询条件空出一行;没有查询条件就要退两行)
for (int i = 0; i < columnNames.length; i++) {// 总列数
label = new Label(i, 2 + conditions.length - notCondition,
columnNames[i]);// 从第2+conditions.length行开始
sheet.addCell(label);
}
// 4插入列表信息(从第3+conditions.length行开始,与查询条件空出一行;没有查询条件就要退两行)
int count = 0;// 定义计数器,用于标记下一行;
for (int j = 0; j < list.size() / columnNames.length; j++) {
for (int i = 0; i < columnNames.length; i++) {// 总列数
if (list.get(i + count) != null
&& !list.get(i + count).equals("")) {
label = new Label(i, j + 3 + conditions.length
- notCondition, list.get(i + count).toString());// 从第3+conditions.length行开始
sheet.addCell(label);
}
}
count += columnNames.length;
}
// 写入数据并关闭文件
book.write();
book.close();
// 下载该文件到本地
downLoad(unloadPath + title + ".xls", response, false);
} catch (Exception e) {
e.printStackTrace();
log4j.error(e);
// Log.error(e);
// 错误接口
}
}
/**
* 获取应用在服务器主机上的实际根目录
*
* @param request
* HttpServletRequest
* @return String
*/
public static String getWebRootPath(HttpServletRequest request) {
return request.getSession().getServletContext().getRealPath("/");
}
public void downLoad(String filePath, HttpServletResponse response,
boolean isOnLine) throws Exception {
File f = new File(filePath);
/*
* if (!f.exists()) { response.sendError(404, "File not found!");
* return; }
*/
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
response.reset(); // 非常重要
// 在线打开方式
if (isOnLine) {
URL u = new URL(filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename="
+ toUTF8(f.getName()));
// 文件名应该编码成UTF-8
}
// 纯下载方式
else {
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename="
+ toUTF8(f.getName()));
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
out.flush();
br.close();
out.close();
}
// UTF-8编码
public String toUTF8(String s) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes("utf-8");
} catch (Exception ex) {
System.out.println(ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0)
k += 256;
sb.append("%" + Integer.toHexString(k).toUpperCase());
}
}
}
return sb.toString();
}
}
此处列举了excel文件导出的方法