生产excel和导出

 //创建excel文件

public static void mikile() {
  final String[] header = new String[] { "name", "sex", "age" };
  final String[][] data = new String[][] { header, { "日日", "F", "22" },
    { "Tom", "M", "25" }, { "Lily", "F", "19" } };

  File tempFile = new File("C://lixin.csv");
  try {
   CSVWriter writer = new CSVWriter(new FileWriter(tempFile));
   for (int i = 0; i < data.length; i++) {
    writer.writeNext(data[i]);
   }

   writer.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

 

//导出excel文件

 public static void downloadFile(HttpServletResponse response,
   String fullfileName) throws Exception {
  // String filePath2 = context.getRequest().getRealPath("/");
  // fullfileName是已经生成excel文件(存在数据的)的路径名
  // 例如:e://file/template/454566412221.xls
  if (fullfileName == null || fullfileName.equals(""))
   return;
  File file = null;
  try {
   file = new File(fullfileName);
   FileInputStream fileInputStream = new FileInputStream(file);
   DataInputStream dataInputStream = new DataInputStream(
     fileInputStream);
   byte[] downContext = new byte[dataInputStream.available()];
   dataInputStream.read(downContext);
   fileInputStream.close();
   dataInputStream.close();
   response.reset();
   response.setContentType("application/octet-stream;charset=UTF-8");// 设置内容类型
   response.setHeader("Content-Length", String.valueOf(file.length()));// 获取文件的大小
      response.setHeader("Content-Disposition","attachment;filename=" +"lixin.csv");//显示导出之后的文件名,调用下面的方法
   
      OutputStream outputStream = response.getOutputStream();// 导出文件
   outputStream.write(downContext);// 将数据导出到客户端内存中
   outputStream.flush();
   outputStream.close();
  } catch (Exception e) {
   throw new Exception(e.getMessage());
  } finally {
   if (file.exists()) {
    //file.delete();
   }
  }
 }

 

需添加opencsv-2[1].0.jar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值