最近用了下xls生成和导出excel

本文介绍了一种利用Java生成Excel文件的方法,并提供了从Web应用中下载这些文件的实现细节。通过示例代码展示了如何设置文件路径、进行数据转换及处理文件读写等关键步骤。

注意要引入新的jar


我把jar放到资源里

//生成excel

public static String doExcel(String from, Map beans, String to,HttpServletRequest request) {

    String path =  request.getSession().getServletContext().getRealPath("//template");//模板地址
    String pathdown =  request.getSession().getServletContext().getRealPath("//upload");//上传地址
    XLSTransformer transformer = new XLSTransformer();
    String sfrom = path + File.separator + from;// 模板文件
    String sto = pathdown + File.separator +  to;// 要生成的文件
    try {
        transformer.transformXLS(sfrom, beans, sto);
    } catch (ParsePropertyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    return sto;
}
// 下载
public static void doDownLoad(String path, String name,HttpServletResponse response) {
try {
response.reset();
response.setHeader("Content-disposition","attachment;success=true;filename ="+ URLEncoder.encode(name, "utf-8"));
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
OutputStream fos = null;
InputStream fis = null;
File uploadFile = new File(path);
fis = new FileInputStream(uploadFile);
bis = new BufferedInputStream(fis);
fos = response.getOutputStream();
bos = new BufferedOutputStream(fos);
// 弹出下载对话框
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.flush();
fis.close();
bis.close();
fos.close();
bos.close();
} catch (Exception e) {
 e.printStackTrace();
}
}
@RequestMapping(value = "/execlbanlace")
public String execlbanlace(HttpSession session, HttpServletRequest request, HttpServletResponse response){
       
Map<String,String> map = new HashMap<String,String>();
    List<userResource> list=NumberDao.SearchRes(map);     
    Map<String,Object> beans = new HashMap<String,Object>();
beans.put("balancelist",list);  
IPTimeStamp its= new  IPTimeStamp("");  
String fileName = its.getIPTimeStampRand();
String path=doExcel("号码资源模板.xlsx" , beans , "号码资源_"+fileName+".xlsx",request);
        //     doDownLoad(path, "balance.xls",response);
     
     
      return null;

}

注意模板内代码要和beans的一致


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值