作者:乔山办公网日期:
返回目录:excel表格制作
Ajax直接调百用后台的下载方法是导出不了文件的,原因是ajax无法度接收后台的文件流,所以,需要再次用知window.location=url或者window.open(url)下载; 但是这样操作会有弊端,导出方道法版会调用两次,第一次是ajax进入导出方法,没有报错的话,就第二次进入方法,
所以权不如直接用 window.location=url 下载
public static void queryexcel(String filename,HttpServletRequest request,HttpServletResponse response) throws Exception {
HSSFWorkbook workbook = null;
//读取表头(表字段名)
String[] titles = (String[]) request.getAttribute("titles");
//读取数据库数据
String [] info=(String[]) request.getAttribute("info");
// 创建工作簿实例
workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("sheet1");
workbook.getSheet(null);
HSSFFont font = workbook.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)14);
HSSFCellStyle style = workbook.createCellStyle();
style.setFont(font);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//居中
style.setWrapText(true);
//加载表头数据
HSSFRow titleRow = sheet.createRow(0);
for (int i = 0; i < titles.length; i++) {
HSSFCell cell = titleRow.createCell((short) i);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
//设置编码e799bee5baa6e79fa5e98193e58685e5aeb9361
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(titles[i].toString());
}
if (info != null) {
HSSFRow dataRow = sheet.createRow(1);
for (int i = 0; i < info.length; i++) {
HSSFCell cell = dataRow.createCell((short)i);
sheet.setColumnWidth((short)i, (short)3500);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
//设置编码
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(info[i]);
}
}
//通过数据流下载工作簿
try {
OutputStream out = response.getOutputStream();
response.setHeader("Content-disposition",
"attachment;filename="+toUtf8String(filename+".xls"));
response.setContentType("text ml;charset=utf-8");
request.setCharacterEncoding("UTF-8");
workbook.write(out);
out.flush();
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//中文名
public static String toUtf8String(String s){
StringBuffer sb = new StringBuffer();
for (int i=0;i<s.length();i++){
char c = s.charAt(i);
if (c >= 0 && c <= 255){sb.append(c);}
else{
byte[] b;
try { b = Character.toString(c).getBytes("UTF-8");}
catch (Exception ex) {
System.out.println(ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0) k += 256;
sb.append("%" + Integer.toHexString(k).toUpperCase());
}
}
}
return sb.toString();
}
function getExcel() { var tabHtml = $("#tb_Class").html(); $.post("../Ajax/GetExcel", { tab: encodeURIComponent(tabHtml) }); } Controler: public void GetExcel() { string sHtml = Server.UrlDecode(Request.Form["tab"]); Export