最近做一个东西,要将数据导出到excel表中,以下是代码
import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.struts2.ServletActionContext; import com.sun.org.apache.regexp.internal.recompile; import entity.CRFHead; import entity.CRFItem; public class crfAction { private List dataList = new ArrayList(); public String initInfo() { dataList .add("1"); dataList .add("2"); dataList .add("3"); dataList .add("4"); HttpServletResponse response = ServletActionContext.getResponse(); setResponseHeader(response,"test.xls"); try { exportQuery(response.getOutputStream(),dataList); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { // TODO: handle exception } //数据导出后缓冲区清空 dataList.clear(); RESPONSE_LABEL=1; return "success"; } /** * 设置输出流及输出文件的编码 * @param response * @param filename1 */ public void setResponseHeader(HttpServletResponse response,String filename1){ try { response.setContentType("application/msexcel;charset=UTF-8"); response.setHeader("content-disposition", "attachment;filename="+java.net.URLEncoder.encode(filename1, "UTF-8")); //System.out.println("a"); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); } catch (Exception e) { e.printStackTrace(); } } public void exportQuery(OutputStream os,List list){ /创建一个工作簿 HSSFWorkbook workbook = new HSSFWorkbook(); //创建单元格,并设置剧中显示 HSSFCellStyle style = workbook.createCellStyle();//创建个表格格式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置格式为居中 //创建一个表单 HSSFSheet sheet = workbook.createSheet("aa"); //在sheet中添加表头第0行 HSSFRow row = sheet.createRow((int)0); //设置表头 HSSFCell cell = row.createCell((short)0); cell.setCellStyle(style); cell.setCellValue("第一列"); cell = row.createCell((short)1); cell.setCellStyle(style); cell.setCellValue("第二列"); cell = row.createCell((short)2); cell.setCellStyle(style); cell.setCellValue("第三列"); cell = row.createCell((short)3); cell.setCellStyle(style); cell.setCellValue("第四列"); row.createCell((short)0).setCellValue(list.get(0)); row.createCell((short)1).setCellValue(list.get(1)); row.createCell((short)2).setCellValue(list.get(2)); row.createCell((short)3).setCellValue(list.get(3)); try{ workbook.write(os); }catch(Exception e){ e.printStackTrace(); } } }