java导出excel

1 篇文章 0 订阅

按钮

<form name="searchfrm" action="myReport!getDataList.action" method="post">
      <div class="searchbar_mid">
          <table cellpadding="0" cellspacing="1" class="content" width="100%">        
            <tr>
              <td>日期:</td>
              <td colspan="4">
              <input type="text" value="${time_start!''}" name="time_start" id="time_start"  />
                到:<input type="text" value="${time_end!''}" name="time_end" id="time_end" />
                </td>
       <td colspan="1">
<input type="submit" class="btn_blue" value="搜索" >
   <input type="button" class="btn_blue" value="导出" onclick="getExcel()" />
          </td>
</tr>
</table>
   </div>
 </form>

异步请求

function getExcel(){
            var param = "";//参数
            var frm = document.searchfrm;
            var time_start = frm.time_start.value;
            if(trim(time_start) != null) {
                param += "&time_start=" + time_start;
            }
            var time_end = frm.time_end.value;
            if(trim(time_end) != null) {
                param += "&time_end=" + time_end;
            }
            var url = "myReport!getReportExcel.action?1=1";
            var myAjax=new Ajax.Request(url,{method:'post',parameters:param,onComplete:retExcel,onError:error});
        }
    //回调函数
    function retExcel(response){
          var ret = eval('(' + response.responseText + ')');
          if(ret.res==1){
              if(ret.execle != null){
                  window.location.href = ret.execle;
              }
          } else {
              alert(ret.message);
          }
      }

java代码

public void getRealNameDataListExcel(){
        HttpServletRequest req = ServletActionContext.getRequest();
        String time_start = req.getParameter("time_start");
        String time_end = req.getParameter("time_end");
        Map map = new HashMap();

        if( StringUtils.isNotEmpty(time_start) ){
            map.put("time_start", time_start.trim());
        }
        if( StringUtils.isNotEmpty(time_end) ){
            map.put("time_end", time_end.trim());
        }
        //没有时间默认最近一个月的
        if( StringUtils.isEmpty(time_start) && StringUtils.isEmpty(time_end) ){
            String today = FLDateUtil.getToday();
            String monthAgo = FLDateUtil.getMonthAgo();
            map.put("start_time", monthAgo);
            map.put("end_time", today);
        }

        try {
            //查询汇总
            int count = reportService.getRealnameDataListByDateCount(map);
            if(count != 0){
                List<Map> data = reportService.getRealNameDataListExcel(map);
                net.sf.json.JSONObject json = new net.sf.json.JSONObject();
                String execle = null;
                if(data != null && data.size() > 0){
                    String [] title = {"日期","芝麻信用通过","芝麻信用未通过","芝麻信用总数","诺证通通过","诺证通未通过","诺证通总数"};//标题排序
                    String[] keys = {"date","zhima_pass_num","zhima_unpass_num","zhima_sub_record","nuozt_pass_num","nuozt_unpass_num","nuozt_sub_record"};//标题排序
                    execle = ExcelUtil.makeExcel("REAlNAMEREPORT", title, keys, data);
                }
                json.put("res", 1);
                if(StringUtil.isNotBlank(execle)){
                    json.put("execle", execle);
                }
                ServletActionContext.getResponse().setCharacterEncoding("utf-8");
                json.write(ServletActionContext.getResponse().getWriter());
            }
        }catch(Exception e){
            FlLogUtils.INSTANCE.logStackTrace(e);
        }
    }

第二个例子

public void getAnswerListExcel(){
        HttpServletRequest req = ServletActionContext.getRequest();
        String time_start = req.getParameter("time_start");
        String time_end = req.getParameter("time_end");
        Map map = new HashMap();

        if( StringUtils.isNotEmpty(time_start) ){
            map.put("time_start", time_start.trim());
        }
        if( StringUtils.isNotEmpty(time_end) ){
            map.put("time_end", time_end.trim());
        }
        //没有时间默认最近一个月的
        if( StringUtils.isEmpty(time_start) && StringUtils.isEmpty(time_end) ){
            String today = FLDateUtil.getToday();
            String monthAgo = FLDateUtil.getMonthAgo();
            map.put("time_start", monthAgo);
            map.put("time_end", today);
        }

        try {
            List<Map> data = answerTotalService.getAnswerListExcel(map);
            JSONObject json = new JSONObject();
            String execle = null;
            if(data != null && data.size() > 0){
                String [] title = {"日期","参与答题总人数","买活总能量","获奖总人数","活动期号","场次","参与答题人数",
                        "买活能量","买活次数","复活卡复活次数","获奖人数","人均获奖金额","获奖积分转能量率","用户作答总次数"};//标题排序
                String[] keys = {"date","answerTotalPeople","buyLiveTotalEnergy","winTotalPeople","activityid","sessionTime","answerPeople",
                        "buyLiveEnergy","buyLiveCount","reviveCount","winPeople","perReward","rewordToEnergyRate","userAnswerTotalCount"};//标题排序
                execle = ExcelUtil.makeExcel("ANSWERTOTAL", title, keys, data);
            }
            json.put("res", 1);
            if(StringUtil.isNotBlank(execle)){
                json.put("execle", execle);
            }
            ServletActionContext.getResponse().setCharacterEncoding("utf-8");
            json.write(ServletActionContext.getResponse().getWriter());

        }catch(Exception e){
            FlLogUtils.INSTANCE.logStackTrace(e);
        }

    }

ExcelUtil工具类

package com.ytfl.master.common;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import com.jack.util.StringUtils;
import com.ytfl.log.FlLogUtils;

/**
 * EXCEL
 * @author dlf
 *
 */
public class ExcelUtil {

    public final static String COL_NAME ="col"; 

    /**
     * 多个sheet
     * @param filename
     * @param data:List<Map>:
     * Map item:
     *  sheet:sheet name
     *  title:title array for this sheet
     *  key: data key array for this sheet
     *  data:data list for this sheet
     * @return
     * @throws Exception
     */
    public static String makeExcel(String filename, List<Map> data)  throws Exception{
        if(filename == null || filename.trim().length() == 0 || data == null || data.size() == 0) return "";
        String webname = "";

        String ename =  GlobalConfig.getProperty("diskpath")+filename+".xls";
        webname = ename.replace(GlobalConfig.getProperty("diskpath"), GlobalConfig.getProperty("webpath"));
        WritableWorkbook book = Workbook.createWorkbook(new File(ename));
        for(int sheetid =0;sheetid < data.size(); sheetid++) {
            Map item = data.get(sheetid);
            String sheetname = (String) item.get("sheet");
            String[] title = (String[]) item.get("title");
            String[] key = (String[]) item.get("key");
            List<Map> sheetdata = (List<Map>) item.get("data");
            WritableSheet sheet = book.createSheet(sheetname, sheetid);
             int i = 0;
             for(String s : title){//第一行标题
                Label label = new Label(i, 0, s);
                i++;        
                sheet.addCell(label);
             }
             for(int j = 0; j < sheetdata.size(); j ++) {
                Map ditem = sheetdata.get(j);
                if(ditem == null) break;
                for(int k = 0; k < key.length; k++) {               
                    String d = null;
                    try {
                        d = ditem.get(key[k]).toString();
                    } catch(Exception e){};
                    if(d == null) d = "";
                    Label label = new Label(k, j+1, d);
                    sheet.addCell(label);
                }
                 // 写入数据并关闭文件 
             }
        }
        book.write();
        book.close();
        return webname;
    }
    public static String makeExcel(String filename, String[] stitle, String[] keys, List<Map>data) throws Exception{
        String webname = "";
        SimpleDateFormat myfmt = new SimpleDateFormat("yyyy-MM-dd-hh-mm");
        String date = myfmt.format(new java.util.Date()).toString();
        String ename =  GlobalConfig.getProperty("diskpath")+"FL"+filename+date+".xls";
        webname = ename.replace(GlobalConfig.getProperty("diskpath"), GlobalConfig.getProperty("webpath"));
        WritableWorkbook book = Workbook.createWorkbook(new File(ename));
        // 生成名为“第一页”的工作表,参数0表示这是第一页
        WritableSheet sheet = book.createSheet("Sheet1", 0);
        int i = 0;
        for(String s : stitle){//第一行标题
            Label label = new Label(i, 0, s);
            i++;        
            sheet.addCell(label);
        }
        for(int j = 0; j < data.size(); j ++) {
            Map item = (Map)data.get(j);
            if(item == null) break;
            for(int k = 0; k < keys.length; k++) {              
                String d = null;
                try {
                    d = item.get(keys[k]).toString();
                } catch(Exception e){};
                if(d == null) d = "";
                Label label = new Label(k, j+1, d);
                sheet.addCell(label);
            }
            // 写入数据并关闭文件 
        }
        book.write();
        book.close();
        return webname;

    }

    public static String makeExcel(String title,String filename, String[] stitle, String[] keys, List<Map>data) throws Exception{
        String webname = "";
        SimpleDateFormat myfmt = new SimpleDateFormat("yyyy-MM-dd-hh-mm");
        String date = myfmt.format(new java.util.Date()).toString();
        String ename =  GlobalConfig.getProperty("diskpath")+"FL"+filename+date+".xls";
        webname = ename.replace(GlobalConfig.getProperty("diskpath"), GlobalConfig.getProperty("webpath"));
        WritableWorkbook book = Workbook.createWorkbook(new File(ename));
        // 生成名为“第一页”的工作表,参数0表示这是第一页
        WritableSheet sheet = book.createSheet("Sheet1", 0);
        int i = 0;
        if(!StringUtils.isEmpty(title)){
            Label label = new Label(i, 0, title);
            sheet.mergeCells(0,0,4,0); 
            sheet.setRowView(0,200); 
            sheet.addCell(label);

        }
        for(String s : stitle){//第一行标题
            Label label = new Label(i, 1, s);
            i++;        
            sheet.addCell(label);
        }
        for(int j = 0; j < data.size(); j ++) {
            Map item = (Map)data.get(j);
            if(item == null) break;
            for(int k=0; k < keys.length; k++) {                
                String d = null;
                try {
                    d = item.get(keys[k]).toString();
                } catch(Exception e){};
                if(d == null) d = "";
                Label label = new Label(k, j+2, d);
                sheet.addCell(label);
            }
            // 写入数据并关闭文件 
        }
        book.write();
        book.close();
        return webname;

    }
    /**
     * 
     * @param elist
     * @param mtitle //标题头
     */
    public static String outExcelByList(List elist,String [] stitle){
        //if(elist == null || elist.size() == 0)return;
        String webname = null;
        try{
            // 打开文件
            SimpleDateFormat myfmt = new SimpleDateFormat("yyyy-MM-dd-hh-mm");
            String date = myfmt.format(new java.util.Date()).toString();
            String ename =  GlobalConfig.getProperty("diskpath")+"FL"+date+".xls";
            webname = ename.replace(GlobalConfig.getProperty("diskpath"), GlobalConfig.getProperty("webpath"));
            WritableWorkbook book = Workbook.createWorkbook(new File(ename));
            // 生成名为“第一页”的工作表,参数0表示这是第一页
            WritableSheet sheet = book.createSheet("第一页", 0);
            // 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
            // 以及单元格内容为test

            for(int j = 1;j<=elist.size();j++){
                int i = 0;
                for(String s : stitle){//第一行标题
                    Label label = new Label(i, 0, s);
                    i++;
                    // 将定义好的单元格添加到工作表中
                    sheet.addCell(label);
                }
                int k = 0;
                Object o = elist.get(j-1);
                if(o == null)
                    continue;
                Map<String,String> m = (Map)o;
                Iterator it = m.entrySet().iterator();
                for(Map.Entry entry:m.entrySet()){
                    System.out.println(entry.getKey()+"="+entry.getValue());
                    sheet.addCell(new Label(k, j, entry.getValue()+""));
                     k++;
                }

            }

            // 写入数据并关闭文件
            book.write();
            book.close();

        }catch(Exception e){
            FlLogUtils.INSTANCE.logStackTrace(e);
        }
        return webname;
    }

     /**
     * 读取Excel数据到内存
     */
    public static List readExcel(FileInputStream file) {
        Workbook book = null;
        List<Map> list = null;
        try {
            // 打开文件
            book = Workbook.getWorkbook(file);
            // 获得第一个工作表对象
            Sheet sheet = book.getSheet(0);
            int rows=sheet.getRows();
            int columns=sheet.getColumns();
            list=new ArrayList<Map>();
            // 遍历每行每列的单元格
            for(int i=0;i<rows;i++){
                Map map = new HashMap(); 
                for(int j=0;j<columns;j++){
                    Cell cell = sheet.getCell(j, i);
                    String result = cell.getContents();
                    if(StringUtils.isEmpty(result)){
                        break;
                    }
                    map.put(COL_NAME+(j+1), result);
                }
                if(map.size()>0){
                    list.add(map);
                }
            }
        } catch (Exception e) {
            FlLogUtils.INSTANCE.logStackTrace(e);
        }finally{
            if(book!=null){
                try {
                    book.close();
                } catch (Exception e) {
                    FlLogUtils.INSTANCE.logStackTrace(e);
                } 
            }
        }
        return list;

    }

    public static void main(String args[]) {//需要处理MAP顺序
        ExcelUtil ex = new ExcelUtil();
        List mlist = new ArrayList();
        Map m = new LinkedHashMap();
        m.put("id", 120);
        m.put("code", "ACML003");
        m.put("pname", "大车车");
        m.put("intecount", "015000");
        m.put("count", "015");
        m.put("state", "待发货");
        m.put("createtime", "2013-6-19 16:00:15");
        mlist.add(m);
        String [] stitle = {"奖品ID","奖品编码","奖品名称","积分价格","限兑数","状态","添加时间","采购价格"};
        ex.outExcelByList(mlist, stitle);
    }

    /**
     * 读取Excel数据到内存:允许空行,固定位置导入
     * nhd:私用
     */
    public static List readExcelBlankLine(FileInputStream file) {
        Workbook book = null;
        List<Map> list = null;
        try {
            // 打开文件
            book = Workbook.getWorkbook(file);//获取excel文件
            // 获得第一个工作表对象
            Sheet sheet = book.getSheet(0);//获取第0个sheet
            //int rows=sheet.getRows();//获取sheet有多少行:
            int preRows = 13;//设置只读取前13行
            int columns=sheet.getColumns();//获取excel有多少列:
            //int preColumns = 8;
            list=new ArrayList<Map>();
            // 遍历每行每列的单元格
            for(int i=0; i<preRows; i++){
                Map map = new HashMap();
                for(int j=0; j<columns; j++){
                    Cell cell = sheet.getCell(j, i);//坐标(0,0)左上角元素;坐标(j,i),第i行第j列的元素;
                    String result = cell.getContents();
                    map.put(COL_NAME+(j+1), result);
                }
                list.add(map);

            }
        } catch (Exception e) {
            FlLogUtils.INSTANCE.logStackTrace(e);
        }finally{
            if(book!=null){
                try {
                    book.close();
                } catch (Exception e) {
                    FlLogUtils.INSTANCE.logStackTrace(e);
                }
            }
        }
        return list;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值