package com.css.common.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;
import com.css.common.util.DateUtil;
import com.opensymphony.xwork2.ActionSupport;
public class BaseExcelAction extends ActionSupport implements
ServletResponseAware, ServletContextAware {
private static final Log log = LogFactory.getLog(BaseExcelAction.class);
private static final long serialVersionUID = 1L;
private HttpServletResponse response;
private ServletContext servletContext;
protected String excelExport() throws Exception {
response.setContentType("text/html");
try {
String contextTitle = "百强问题调查信息表";
String realPath = servletContext.getRealPath("/");
log.debug("realPath=" + realPath);
List columnContextList = new ArrayList();
// 拼装
excelExport(realPath, contextTitle, columnContextList);
} catch (Exception e) {
log.fatal("导出问卷信息结束", e);
}
return NONE;
}
/**
* 从DB中导出数据到Excel
*/
protected void excelExport(String realPath, String contextTitle,
List columnContextList) throws Exception, FileNotFoundException,
IOException {
// 把数据写入Excel
if (columnContextList != null) {
String fileName = DateUtil.getLocalDateTime() + ".xls";
IExcelExport excel = new QuesExcelExportUtil(contextTitle,columnContextList);
// 1.输出到指定文件夹
excel.exportExcel(new File(realPath + fileName));
log.debug("fileName=" + fileName);
log.debug("恭喜您!Excel导出成功");
File file = new File(realPath + fileName);
long _l = file.length();
InputStream in = new FileInputStream(file);
if (in != null) {
response.reset();
response.setContentType("application/x-msdownload");
response.setHeader("Content-disposition","attachment; filename=" + fileName);
// 以上输出文件元信息
response.setContentLength((int) _l); // 设置输入文件长度
byte[] _b = new byte[2048];
int _llen = 0;
while ((_llen = in.read(_b)) > 0) {
response.getOutputStream().write(_b, 0, _llen); // 向浏览器输出
}
in.close(); // 关闭文件输入流
response.flushBuffer();
}
new File(realPath + fileName).delete();
}
}
/**
* 从Excel中导入数据到DB
*/
protected void excelImport(){
//
}
public void setServletResponse(HttpServletResponse response) {
this.response = response;
}
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
}