使用poi操作导出excel代码示例

package pi3000.narris.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/***
 * 通过AJAX示例,导出EXCEL示例:
 * JAVA中采用HSSFWorkbook创建EXCEL表格,设置输出格式输出
 * @author huawei
 *
 */
public class ExportExcelServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

 protected void service(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String method = request.getParameter("method");
  if("prestartExcel".equals(method)){
   prestartExcel(request, response);
  }else if("downloadExcel".equals(method)){
   downloadExcel(request, response);
  }
 }

 private void prestartExcel(HttpServletRequest request, HttpServletResponse response) {
  //产生的Excel文件的名称
  //产生工作簿对象
  HSSFWorkbook workbook = new HSSFWorkbook();
  //产生工作表对象
  HSSFSheet sheet = workbook.createSheet();
  
  //创建生成EXCEL头部
  List<String> lists = getExcelHeader();
  createExcelHeader(workbook, sheet, lists);//sheet表、单元格样式、数据集合
  
  //创建生成EXCEL实体数据
  Map<String, List<Object>> maps = getExcelBody();
  createExcelBody(workbook, sheet, maps);//sheet表、body的数据集合
  
  HttpSession session = request.getSession();
  session.setAttribute("excel", workbook);
 }

 private void createExcelHeader(HSSFWorkbook workbook, HSSFSheet sheet, List<String> lists) {
  //设置第一个工作表的名称为firstSheet
  workbook.setSheetName(0,"自动化设备检修");
  sheet.setDefaultColumnWidth(15);//设置默认每一列的宽度
  //sheet.setDefaultRowHeight((short) (20 * 20));//设置默认每一行的行高
  //产生第二个工作表对象 HSSFSheet sheet2 = workbook.createSheet();
  //设置第二个工作表的名称为secondSheet  workbook.setSheetName(1,"自动化设备检修2");
  //设置单元格样式:可以对字体、前景色、背景色等设置,参考POI的API
  HSSFCellStyle cellStyle = workbook.createCellStyle();
  HSSFFont font = workbook.createFont();
  font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//设置粗体
  cellStyle.setFont(font);
  HSSFRow row = sheet.createRow(0);
  HSSFCell cell = null;
  for(int i = 0;i < lists.size();i++){
   cell = row.createCell(i);
   cell.setCellValue(lists.get(i));
   cell.setCellStyle(cellStyle);
  }
 }

 private void createExcelBody(HSSFWorkbook workbook, HSSFSheet sheet, Map<String, List<Object>> maps) {
  //定义单元格样式
  HSSFCellStyle cellStyle = workbook.createCellStyle();
  HSSFDataFormat dataFormat = workbook.createDataFormat();
  cellStyle.setDataFormat(dataFormat.getFormat("yyyy-mm-dd hh:mm"));//时间格式
  cellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);//对齐方式
  
  HSSFRow row;
  HSSFCell cell;
  int rows = maps.keySet().size();
  List<Object> bodylist = null;
  int index = 0;
  for(int i = 0;i < rows;i++){
   bodylist = maps.get(String.valueOf(i));
   if(bodylist != null){
    row = sheet.createRow(++index);
    for(int j = 0;j < bodylist.size();j++){
     cell = row.createCell(j);
     Object data = bodylist.get(j) == null? "" : bodylist.get(j);
     if(data != null && "java.sql.Timestamp".equals(data.getClass().getName())){//判断如果为时间格式则:
      Date date = new Date(((Timestamp)data).getTime());
      cell.setCellValue(date);
      cell.setCellStyle(cellStyle);
     }else{//如果为null、string则:
      cell.setCellValue(data.toString());
     }
    }
   }
  }
 }
 /***
  * 从SESSION中取出EXCEL
  * @param request
  * @param response
  * @throws IOException
  */
 private void downloadExcel(HttpServletRequest request, HttpServletResponse response) throws IOException{
  String filename = "自动化系统设备检修流程";
  HttpSession session = request.getSession();
  HSSFWorkbook workbook = (HSSFWorkbook)session.getAttribute("excel");
  OutputStream out = response.getOutputStream();// 取得输出流  
  response.reset();// 清空输出流  
  response.setCharacterEncoding("UTF-8");
  //设置返回的头字段:http协议inline采用浏览器方式打开、attachment采用本地EXCEL方式打开
  response.setHeader("Content-disposition", "inline;filename = " + java.net.URLEncoder.encode(filename, "UTF-8") + ".xls");
  //response.setHeader("Content-disposition", "attachment;filename = " + java.net.URLEncoder.encode(filename, "UTF-8") + ".xls");
  response.setContentType("application/vnd.ms-excel;charset=UTF-8");//定义输出类型
  workbook.write(out);
  out.flush();
  out.close();
 }
 /***
  * 准备导出EXCEL的头部数据
  * @return
  */
 private List<String> getExcelHeader(){
  List<String> lists = new ArrayList<String>();
  lists.add("申请单号");lists.add("单位名称");
  lists.add("设备名称");lists.add("所属系统名称");
  lists.add("电压等级");lists.add("紧急程度");
  lists.add("维护内容");lists.add("处理日期");
  return lists;
 }
 /***
  * 准备导出EXCEL的实体数据
  * @return
  */
 private Map<String, List<Object>> getExcelBody(){
  Map<String, List<Object>> maps = new HashMap<String, List<Object>>();
  Date date = new Date();//模拟日期数据
  Timestamp timestamp = Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
  Object[][] tabledate =
   {
   {"ZDH_001","变电站1","110kV设备","系统1","220kV","一般","nr_1",timestamp},
   {"ZDH_002","变电站2","111kV设备","系统2","330kV","紧急","nr_2",timestamp},
   {"ZDH_003","变电站3","112kV设备","系统3","440kV","紧急","nr_3",timestamp},
   {"ZDH_004","变电站4","113kV设备","系统4","550kV","一般","nr_4",timestamp},
   {"ZDH_006","变电站5","114kV设备","系统5","660kV","紧急","nr_5",timestamp},
   {"ZDH_007","变电站6","115kV设备","系统6","770kV","一般","nr_6",timestamp},
   {"ZDH_008","变电站7","116kV设备","系统7","880kV","紧急","nr_7",null},
   {"ZDH_009","变电站8","117kV设备","系统8","990kV","一般","nr_8",timestamp}
   };
  Object[] contents = null;
  List<Object> lists = null;
  for(int i = 0;i < tabledate.length;i++){//循环行数
   contents = tabledate[i];
   lists = new ArrayList<Object>();
   for(int j = 0;j < contents.length;j++){//循环列数
    lists.add(contents[j]);
   }
   System.out.print("index: " + i + "  ");
   maps.put(String.valueOf(i), lists);//存放:行号、该行记录内容
  }
  System.out.println();
  return maps;
 }
}

 

 

 

//下面是导出excel的jsp示例,包含浏览器判断的代码

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html version="-//W3C//DTD HTML 4.01 Transitional//EN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="utf-8" src="../javascript/jquery-1.4.3.js"></script>
<script type="text/javascript" language="utf-8" src="../javascript/jquery.form.js"></script>
<title>文件下载</title>
</head>
<script type="text/javascript">
 $(function(){
  /**
  判断浏览器类型和版本信息,如果真的IE浏览器可以直接调用下面的另一种简便方式判断
  var Sys = {};
        var ua = navigator.userAgent.toLowerCase();
        var s;
        (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
        (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
        (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
        (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
        (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
        //以下进行测试
        if (Sys.ie) document.write('IE: ' + Sys.ie);
        if (Sys.firefox) document.write('Firefox: ' + Sys.firefox);
        if (Sys.chrome) document.write('Chrome: ' + Sys.chrome);
        if (Sys.opera) document.write('Opera: ' + Sys.opera);
        if (Sys.safari) document.write('Safari: ' + Sys.safari);
  */
  
  $("#button").click(function(){
   $.ajax({
    type: "POST",
    //async:true,
    data: "method=prestartExcel",
    url: "/web/ExportExcelServlet",
    success: function(e){
     if(navigator.userAgent.indexOf("MSIE 9.0")>0){//其实不需要判断,此处是为了测试调用的效果
      window.open("/web/ExportExcelServlet?method=downloadExcel","_blank");
         ///window.location = "/web/ExportExcelServlet?method=downloadExcel";
     }
    },
    error: function(e){
     alert('下载失败');
    }
   });
  });
  
  $("#submit").submit(function(){
   var filename = $("#file").val();
   if(filename != null && filename != ""){
    var endswith = filename.substring(filename.length - 4, filename.length);
    if(".xls" == endswith){
     return true;
    }else{
     alert("上传文件类型不符合规范,仅限于excel类型文件格式");
    }
   }
   return false;
  });
 });
</script>
<body>
 <input type="button" value="导出EXCEL" id="button"/>
 <br/>
 hello,work,hello,work,fuck,hello,good,ok
 <form enctype="multipart/form-data" id="form" action="../excelOperate?sheet=2" method="post">
  上传附件:<input type="file" id="file" name="file"/>
  <input type="submit" id="submit" value="上传附件"/>
 </form>
</body>
</html>

你可能感兴趣的:(使用poi操作导出excel代码示例)