作者:乔山办公网日期:
返回目录:excel表格制作
Excel导出是无法用ajax的,只能使用window.location.href
好像返回的文本有夹质的,你用alert看下是不是你想要的结果,jquery.ajax提交和获取是用utf-8编码的。看下编码对不对。
e69da5e6ba90e799bee5baa6e79fa5e98193361public 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);
//设置编码
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();
}