导出word,excel

来源:互联网 发布:重庆大数据公司 编辑:程序博客网 时间:2024/04/28 07:25

//后台

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
* Servlet implementation class ServletExportData
*/
public class ServletExportData extends HttpServlet {
private static final long serialVersionUID = 1L;
      
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doPost(request,response);
}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String filename=request.getParameter("filename");
  filename = new String(filename.getBytes("8859_1"), "UTF-8").replaceAll(" ","");
  //filename=convert(filename);
 
  Map<String, List<String>> map=getParams(request, "params"); 
  String title_number[] = map.get("title_number").toArray(new String[]{});
  String term_name[] = map.get("term_name").toArray(new String[]{});
  String term_name_en[] = map.get("term_name_en").toArray(new String[]{});
  String term_name_text[] = map.get("term_name_text").toArray(new String[]{});
  String term_name_text_en[] = map.get("term_name_text_en").toArray(new String[]{});

  try{
   //工作簿
   HSSFWorkbook wb = new HSSFWorkbook();
   //工作sheet
   HSSFSheet sh = wb.createSheet("协议名称");
   HSSFRow rowname = sh.createRow(0);

   //rowname.createCell(0).setCellValue("编号");  //row
   rowname.createCell(0).setCellValue("编号");  //name
   rowname.createCell(1).setCellValue("中文主题");  //name
   rowname.createCell(2).setCellValue("英文主题");  //cn
   rowname.createCell(3).setCellValue("中文条款");  //en
   rowname.createCell(4).setCellValue("英文条款");
   for(int i=1;i<=term_name.length;i++){
    HSSFRow row = sh.createRow(i);

    //row.createCell(0).setCellValue(i);  //row
    row.createCell(0).setCellValue(convert(title_number[i-1]));  //
    row.createCell(1).setCellValue(convert(term_name[i-1]));  //name
    row.createCell(2).setCellValue(convert(term_name_en[i-1]));  //cn
    row.createCell(3).setCellValue(convert(term_name_text[i-1]));  //en
    row.createCell(4).setCellValue(convert(term_name_text_en[i-1]));  //en
    //java.net.URLEncoder.encode()
   }
  
  
   filename= java.net.URLEncoder.encode(filename, "UTF-8");//.replaceAll("+"," ")
  
   response.setContentType("application/x-msdownload");
   response.setCharacterEncoding("UTF-8");
   response.addHeader("Content-Disposition", "attachment; filename=\""+filename+".xls\"");
 
  
     
   ServletOutputStream so = response.getOutputStream();
   //FileOutputStream so = new FileOutputStream(this.getServletContext().getRealPath("/")+"upload"+File.separator+"workbook.xls");
   wb.write(so);
  
   so.flush();
   so.close();
  }catch(Exception e){
   System.out.println(e.getMessage());
  }
}

private String convert(String v) throws Exception{
  //v="5rWL6K+V5Lit5paHZmRhZmRzYWZkc2FmZHNhZmRhcw";
  byte[] b=StringCoder.decode(v.replaceAll(" ", "+").toCharArray());
  String tmp=StringCoder.toStr(b);
  tmp= StringCoder.unescape(tmp);

  return tmp;
}

private Map<String, List<String>> getParams(HttpServletRequest req, String key){
  Map<String, List<String>> arymap=new HashMap<String, List<String>>();
  String tmp=req.getParameter(key);
  tmp=(tmp.startsWith("&"))?tmp.substring(1):tmp;
  String[] ary=tmp.split("&");
  for(int i=0;i<ary.length;i++){
   String[] aa=ary[i].split("=");
   String k=aa[0];
   String v=(aa.length>1)?aa[1]:"";
   if(arymap.containsKey(k)){
    arymap.get(k).add(v);
   }else{
    ArrayList<String> l=new ArrayList<String>();
    l.add(v);
    arymap.put(k, l);
   }
  }
  return arymap;
}
}

////////转码////////////

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class StringCoder {
  private StringCoder() {
  }

  public static void main(String[] args){
   String tmp="测试中文fdafdsafdsafdsafdas";
   System.out.println(tmp);
   tmp=new String(StringCoder.encode(tmp.getBytes()));
   System.out.println(tmp);
   tmp=StringCoder.escape(tmp);
   System.out.println(tmp);
   tmp=StringCoder.unescape(tmp);
   System.out.println(tmp);
   tmp=new String(StringCoder.decode(tmp.toCharArray()));
   System.out.println(tmp);
  
   tmp="JQB1ADYARAA0AEIAJQB1ADgAQgBEADUAJQB1ADQARQAyAEQAJQB1ADYANQA4ADcA";
   char[] c=tmp.toCharArray();
   byte[] t=StringCoder.decode(c);
   tmp=toStr(t);
   System.out.println(tmp);
   System.out.println(StringCoder.unescape(tmp));
  }
 

  public static String toStr(byte[] t){
   byte[] tt=new byte[t.length];
   int j=0;
   for(int i=0;i<t.length;i++){
    if(t[i]>0){
     tt[j]=t[i];
     j++;
    }
   }
   t=Arrays.copyOfRange(tt, 0, j);
   return new String(t);
  }
 
  public static String unescape(String src) {
    StringBuffer tmp = new StringBuffer();
    tmp.ensureCapacity(src.length());
    int lastPos = 0, pos = 0;
    char ch;
    while (lastPos < src.length()) {
      pos = src.indexOf("%", lastPos);
      if (pos == lastPos) {
        if (src.charAt(pos + 1) == 'u') {
          ch = (char) Integer.parseInt(src.substring(pos + 2, pos + 6), 16);
          tmp.append(ch);
          lastPos = pos + 6;
        } else {
          ch = (char) Integer.parseInt(src.substring(pos + 1, pos + 3), 16);
          tmp.append(ch);
          lastPos = pos + 3;
        }
      } else {
        if (pos == -1) {
          tmp.append(src.substring(lastPos));
          lastPos = src.length();
        } else {
          tmp.append(src.substring(lastPos, pos));
          lastPos = pos;
        }
      }
    }
    return tmp.toString();
  }
  public static String escape(String src) {
    int i;
    char j;
    StringBuffer tmp = new StringBuffer();
    tmp.ensureCapacity(src.length() * 6);

    for (i = 0; i < src.length(); i++) {

      j = src.charAt(i);

      if (Character.isDigit(j) || Character.isLowerCase(j) ||
          Character.isUpperCase(j)) {
        tmp.append(j);
      }
      else
      if (j < 256) {
        tmp.append("%");
        if (j < 16) {
          tmp.append("0");
        }
        tmp.append(Integer.toString(j, 16));
      }
      else {
        tmp.append("%u");
        tmp.append(Integer.toString(j, 16));
      }
    }
    return tmp.toString();
  }



  public static byte[] decode(char[] data) {
    int tempLen = data.length;
    for (int ix = 0; ix < data.length; ix++) {
      if ( (data[ix] > 255) || codes[data[ix]] < 0) {
        --tempLen;
      }
    }
    int len = (tempLen / 4) * 3;
    if ( (tempLen % 4) == 3) {
      len += 2;
    }
    if ( (tempLen % 4) == 2) {
      len += 1;
    }
    byte[] out = new byte[len];

    int shift = 0; // # of excess bits stored in accum
    int accum = 0; // excess bits
    int index = 0;

    for (int ix = 0; ix < data.length; ix++) {
      int value = (data[ix] > 255) ? -1 : codes[data[ix]];

      if (value >= 0) {
        accum <<= 6;
        shift += 6;
        accum |= value;
        if (shift >= 8) {
          shift -= 8;
          out[index++] = (byte) ( (accum >> shift) & 0xff);
        }
      }
    }

    if (index != out.length) {
      throw new Error("Miscalculated data length (wrote " + index +
                      " instead of " + out.length + ")");
    }

    return out;
  }

  static public char[] encode(byte[] data) {
    char[] out = new char[ ( (data.length + 2) / 3) * 4];
    //System.out.println(data.length + " " + out.length + " " + ( (data.length + 2) / 3) * 4);

    for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
      boolean quad = false;
      boolean trip = false;

      int val = (0xFF & (int) data[i]);
      val <<= 8;
      if ( (i + 1) < data.length) {
        val |= (0xFF & (int) data[i + 1]);
        trip = true;
      }
      val <<= 8;
      if ( (i + 2) < data.length) {
        val |= (0xFF & (int) data[i + 2]);
        quad = true;
      }
      out[index + 3] = alphabet[ (quad ? (val & 0x3F) : 64)];
      val >>= 6;
      out[index + 2] = alphabet[ (trip ? (val & 0x3F) : 64)];
      val >>= 6;
      out[index + 1] = alphabet[val & 0x3F];
      val >>= 6;
      out[index + 0] = alphabet[val & 0x3F];
    }
    return out;
  }

  static private char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();

  static private byte[] codes = new byte[256];
  static {
    for (int i = 0; i < 256; i++) {
      codes[i] = -1;
    }
    for (int i = 'A'; i <= 'Z'; i++) {
      codes[i] = (byte) (i - 'A');
    }

    for (int i = 'a'; i <= 'z'; i++) {
      codes[i] = (byte) (26 + i - 'a');
    }
    for (int i = '0'; i <= '9'; i++) {
      codes[i] = (byte) (52 + i - '0');
    }
    codes['+'] = 62;
    codes['/'] = 63;
  }
}

////////前台//////////////

<iframe id='downframe' src='downframe.htm' style="display:none;"></iframe>

var docParams='';
var xlsParams='';

function doExpDoc(){
var url="/ServletExportWord?filename="+contract_name;
var frame=$("#downframe")[0];
frame.contentWindow.downloadform.action=url;
frame.contentWindow.downloadform.params.value=docParams;
frame.contentWindow.downloadform.submit();
}
}

function doExpXls(){
var url="/ExportDataToExcel?filename="+contract_name;//?a=b  其他参数
var frame=$("#downframe")[0];
frame.contentWindow.downloadform.action=url;
frame.contentWindow.downloadform.params.value=xlsParams;
frame.contentWindow.downloadform.submit();

}

///////////////////////////

$('.doc').each(function(i){
  var doc_term=escape( $('#title_'+i).html());
  var xls_term='&title_number='+BASE64.base64Encode(escape($('#title_number_'+i).text())).replace("=", "")
           +'&term_name='+BASE64.base64Encode(escape($('#term_name_'+i).text())).replace("=", "")
              +'&term_name_en='+BASE64.base64Encode(escape($('#term_name_en_'+i).text())).replace("=", "")
            +'&term_name_text='+BASE64.base64Encode(escape($('#term_name_text_'+i).text())).replace("=", "")
            +'&term_name_text_en='+BASE64.base64Encode(escape($('#term_name_text_en_'+i).text())).replace("=", "");
  window.xlsParams+=xls_term;
});

window.docParams=BASE64.base64Encode(escape($('#content').html())).replace("=", "");

///'downframe.htm' /////


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>文件下载</title>
    </head>
    <body>
      <form id="downloadform" name="downloadform" method="post"
            action="/ExportDataToExcel">
            <input type="hidden" id="params" name="params" value=""/>
      </form>
    </body>
</html>

////////////BASE64////////////////

var BASE64={

b64ch : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
base64Decode: function (b64)
{
   var i, j, k;
   var c = [0,0,0,0];
   var uba = []; // unicode byte array
   var ucs = ""; // unicode string
   var ch; // single character
   for (j=k=0; ; ) {
     for (i=0; i<4 && k<b64.length; k++) {
     ch = b64.charAt(k);
     switch (ch) {
     case '=' : c[i] = 0; break;
     case '\r':
     case '\n': continue;
     default:
     c[i++] = this.b64ch.indexOf(ch);
     }
     }
     uba.length += 3;
     if (i>0) uba[j++] = (c[0] << 2 | c[1] >>> 4) & 0xff;
     if (i>1) uba[j++] = (c[1] << 4 | c[2] >>> 2) & 0xff;
     if (i>2) uba[j++] = (c[2] << 6 | c[3]) & 0xff;
     if (i<4) break;
   }
   if (uba.length % 2 != 0) uba.length--;
   for (j=0; j<uba.length; j+=2) {
     ch = (uba[j] | uba[j+1] << 8).toString(16);
     ch = "0000".substring(ch.length) + ch;
     ucs += unescape("%u"+ch);
   }
   return ucs;
},
base64Encode : function (str, flag)
{
   var i, j, k;
   var b = [0,0,0];
   var uba = []; // unicode byte array
   var b64 = ""; // the base64 string
   var len; // length of base64 string
   var ch; // single character
   for (j=0,k=0; j<str.length; j++) {
     ch = str.charCodeAt(j);
     uba.length += 2;
     uba[k++] = ch & 0xff;
     uba[k++] = ch >>> 8;
   }
   for (j=k=len=0; ; ) {
     b[0] = b[1] = b[2] = 0;
     for (i=0; i<3 && j<uba.length; i++,j++)
     b[i] = uba[j];
     if (i==0) break;
     b64 += this.b64ch.charAt([b[0] >>> 2]);
     b64 += this.b64ch.charAt((b[0] & 0x03) << 4 | b[1] >>> 4);
     b64 += i>1 ? this.b64ch.charAt((b[1] & 0x0f) << 2 | b[2] >>> 6) : "=";
     b64 += i>2 ? this.b64ch.charAt(b[2] & 0x3f) : "=";
     len += 4;
     if (flag && len%76==0) b64 += "\r\n";
   }
   return b64;
}
};

原创粉丝点击