1,获取服务器现有excel文件

public List<Object[]> getObject(String filePath){

        log.info("**文件路径为:**"+filePath);

        List<Object[]> mediacelList = new ArrayList<Object[]>();

        // 构造 Workbook 对象,execelFile 是传入文件路径(获得Excel工作区)
Workbook book = null;
try
{
book = new HSSFWorkbook(new FileInputStream(filePath));
} catch (Exception e)
{
e.printStackTrace();
log.error("***获取服务器文件***",e);
} // 读取表格的第一个sheet页
Sheet sheet = book.getSheetAt(0); // 定义 row、cell
Row row; // 总共有多少行,从0开始
int totalRows = sheet.getLastRowNum() ; // 循环输出表格中的内容,首先循环取出行,再根据行循环取出列
for (int i = 0; i <= totalRows; i++) { Object[] ob = new Object[23]; row = sheet.getRow(i); // 处理空行
if(row == null){
continue ;
} // 总共有多少列,从0开始
int totalCells = row.getLastCellNum() ; for (int j = 0; j < totalCells; j++) { Object cell = row.getCell(j);
ob[j] = cell;
}
mediacelList.add(ob);
}
return mediacelList;
}

2,将步骤1返回的数据转换成excel所需要的字符串格式

    private String dataToString(List data) {

        StringBuffer temp = new StringBuffer();

        if (data != null && data.size() > 0) {

            for (int i = 0; i < data.size(); i++) {
Object[] obj = (Object[]) data.get(i);
if (obj == null)
break;
for (int j = 0; j <= obj.length - 2; j++) {
if (obj[j] == null) {
log.info("obj[j]为空===============" + obj[j]);
temp.append(" \t");
} else {
log.info("obj[" + j + "]==========================="
+ obj[j]);
temp.append(obj[j].toString() + " \t");
}
}
if (obj[obj.length - 1] == null) {
temp.append(" \n");
} else {
temp.append(obj[obj.length - 1].toString() + "\n");
}
}
}
return temp.toString();
}

3,执行下载功能

    @RequestMapping("/downLoadFailRecord")
public ModelAndView downLoadFailRecord(
HttpServletRequest request,HttpServletResponse response,
@ModelAttribute("filePath")String filePath) throws Exception{ log.info("=========下载啦啦啦啦=======进入downLoadFailRecord===========filePath:"+filePath); String excelData = ""; String str = "医路通保存失败统计记录"; excelData = medicalService.getFailMedical(filePath); log.info("*******解析的字符串为:"+excelData); response.setContentType("application/ms-txt;charset=UTF-8");
response.addHeader("Content-Disposition","attachment; filename=" + new String(str.getBytes("GBK"),"ISO8859_1") + ".xls");
response.getWriter().write(excelData);
return null;
}

ps:excel文件的xls格式默认纯数字的数据将不能正常显示,所以根据实际经验下载excel文件时设置成csv体验会更好一点

步骤如下:

2,2,将步骤1返回的数据转换成excel所需要的字符串格式,各个字段用逗号(,)隔开

    private String dataToString(List data) {

        StringBuffer temp = new StringBuffer();

        if (data == null || data.size() <= 0) {
return null;
} for (int i = 0; i < data.size(); i++) { Object[] obj = (Object[]) data.get(i); if (obj == null){
break;
} for (int j = 0; j <= obj.length - 2; j++) { if (obj[j] == null) {
temp.append(" ,");
} else {
temp.append(obj[j].toString() + " \t,");
}
} if (obj[obj.length - 1] == null) {
temp.append(" \n");
} else {
temp.append(obj[obj.length - 1].toString() + "\n");
}
} return temp.toString();
}

3,2执行下载功能

    @RequestMapping("/downLoadFailRecord")
public ModelAndView downLoadFailRecord(
HttpServletRequest request,HttpServletResponse response,
@ModelAttribute("filePath")String filePath) throws Exception{ log.debug("====进入downLoadFailRecord===========filePath:"+filePath); String excelData = ""; String str = "医路通失败统计记录"; excelData = medicalService.getFailMedical(filePath); response.setContentType("application/ms-txt;charset=UTF-8");
response.addHeader("Content-Disposition","attachment; filename=" + new String(str.getBytes("GBK"),"ISO8859_1") + ".csv");
response.getWriter().write(excelData);
return null;
}

拓展:有时候下载的csv存在乱码,则把csv文件另存为...一下就好了,就好了,尽然就好了!!!

java实现下载excel功能的更多相关文章

  1. Java中读取Excel功能实现_POI

    这里使用apache的poi进行读取excel 1,新建javaproject 项目:TestExcel 2,导入包 包下载地址:http://poi.apache.org/download.html ...

  2. Java 批量下载excel,并对excel赋值,压缩为zip文件(POI版)

    package com.neusoft.nda.servlet; import java.io.File;import java.io.FileInputStream;import java.io.F ...

  3. java实现导入excel功能

    实现功能: 1.Excel模板下载 2.导入excel 一.jsp效果和代码 <form id="uploadForm" target="frameFile&quo ...

  4. JAVA实现导出excel功能,封装通用导出工具类

    引入maven <!--excel导出--> <dependency> <groupId>net.sourceforge.jexcelapi</groupId ...

  5. java的poi技术下载Excel模板上传Excel读取Excel中内容(SSM框架)

    使用到的jar包 JSP: client.jsp <%@ page language="java" contentType="text/html; charset= ...

  6. 【小坑】java下载excel文件

    excel文件的导入导出是很常见的功能,这次做了个下载的功能,踩了一些坑,记下来避免以后重复踩…… 1.inputstream序列化问题 Could not write JSON document: ...

  7. Java浏览器下载文件为excel(springMVC方式)

    action中的方法 /** * Excel文件下载处理 * @return */ @RequestMapping("/downloanExcel") public ModelAn ...

  8. java、jsp导出excel功能备份

    问题踩坑: ajax请求不能下载文件 必须这样: <a href="/media">点击下载Excel</a> 或者 location.href = '/m ...

  9. JAVA web端JS下载excel文件

    JSP代码如下: JSP端引入jquery.easyui.min.js库: <script type="text/javascript" src="<c:ur ...

随机推荐

  1. prototype.js的Ajax对IE8兼容问题解决方案

    你是否遇到过这样的问题?在使用protype.js的Ajax应用时,会出现这样的问题:只要调用了Ajax.Request,然后点该页面右键,查看“属性”就弹出“IE停止工作”的对话框,然后强制重新加载 ...

  2. eigen Matrix详解

    Eigen Matrix 详解 在Eigen中,所有的matrices 和vectors 都是模板类Matrix 的对象,Vectors 只是一种特殊的矩阵,行或者列为1. Matrix的前三个模板参 ...

  3. oracle 单表导出导入

    exp username/password@服务名 file=d:\daochu.dmp tables=(tableneme,...)

  4. BZOJ1855 股票交易 单调队列优化 DP

    描述 某位蒟佬要买股票, 他神奇地能够预测接下来 T 天的 每天的股票购买价格 ap, 股票出售价格 bp, 以及某日购买股票的上限 as,  某日出售股票上限 bs, 并且每次股票交 ♂ 易 ( 购 ...

  5. Python3字符编码

    编码 字符串是一种数据类型,但是,字符串比较特殊的是还有一个编码问题. 因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理.最早的计算机在设计时采用8个比特(bit)作为一个字节 ...

  6. Laravel policy 的应用

    Laravel 提供更简单的方式来处理用户授权动作.类似用户认证,有 2 种主要方式来实现用户授权:gates 和策略,我这里主要讲解下策略的使用. 文档 上面有详细的说明,我这里只根据自己使用过程做 ...

  7. PhpStorm 为 Laravel 搭建 PhpUnit 单元测试环境

    1.PhpStorm 中打开项目的路径为 Laravel 安装的根目录 2.点击右下角 EventLog 提示按钮, 初始化 Composer 的设置 3.打开单元单测试示例类,按提示点击 Fix . ...

  8. QueryRunner类的八种结果处理集

    package cn.jy.demo; import java.sql.Connection; import java.sql.SQLException; import java.util.List; ...

  9. IOS初级:NSKeyedArchiver

    NSKeyedArchiver对象归档 首先要实现<NScoding>里面的两个代理方法initWithCoder,encodeWithCoder @property (nonatomic ...

  10. 阻塞式简易http服务器

    说明         使用java.net包的ServerSocket也是阻塞的,所以下面的实例把ServerSocketChannel换成ServerSocket效果一样. 后台代码 package ...