代码如下(示例):
pom.xml
<dependency>
<groupId>net.sf.jxlsgroupId>
<artifactId>jxls-coreartifactId>
<version>1.0.6version>
<scope>compilescope>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poiartifactId>
<version>3.17version>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poi-scratchpadartifactId>
<version>3.17version>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poi-ooxmlartifactId>
<version>3.17version>
dependency>
ExcelUtiles
package com.src.common.excel;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.ResourceUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
/**
* @ProjectName: Student
* @Package: cn.utils
*/
public class ExcelUtiles {
/**
* 输出表格
* @param map 表格中数据
* @param response 响应
* @param excelName 表格名称
* @param excelPath 表格模板保存的路径
*/
public static void outExcel(Map<String,Object> map,HttpServletResponse response,String excelName,String excelPath){
File file=null;
try {
file= ResourceUtils.getFile(excelPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//配置下载路径
String path = StaticUrl.getFileUrl()+"down\\";
createDir(new File(path));
//根据模板生成新的excel
File excelFile = createNewFile(map, file, path,excelName);
//浏览器端下载文件
try {
downloadFile(response, excelFile,excelName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//删除服务器生成文件
deleteFile(excelFile);
}
/**
* 根据excel模板生成新的excel
* @param beans 表格中的数据
* @param file 文件
* @param path 生成文件的位置
* @param excelName 文件名称
* @return
*/
private static File createNewFile(Map<String, Object> beans, File file, String path,String excelName) {
XLSTransformer transformer = new XLSTransformer();
File newFile = new File(path + excelName+".xls");
try (InputStream in = new BufferedInputStream(new FileInputStream(file));
OutputStream out = new FileOutputStream(newFile)) {
Workbook workbook = transformer.transformXLS(in, beans);
workbook.write(out);
out.flush();
return newFile;
} catch (Exception e) {
System.out.println(e.getMessage());
}
return newFile;
}
/**
* 将服务器新生成的excel从浏览器下载
* @param response 响应
* @param excelFile 表格文件
* @param excelName 表格名称
* @throws UnsupportedEncodingException
*/
private static void downloadFile(HttpServletResponse response, File excelFile,String excelName) throws UnsupportedEncodingException {
/* 设置文件头:最后一个参数是设置下载文件名 */
response.setHeader("Content-type","application/vnd.ms-excel");
// 解决导出文件名中文乱码
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition","attachment;filename="+new String(excelName.getBytes("UTF-8"),"ISO-8859-1")+".xls");
try (
InputStream ins = new FileInputStream(excelFile);
OutputStream os = response.getOutputStream()
) {
byte[] b = new byte[1024];
int len;
while ((len = ins.read(b)) > 0) {
os.write(b, 0, len);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 浏览器下载完成之后删除服务器生成的文件
* 也可以设置定时任务去删除服务器文件
*
* @param excelFile
*/
private static void deleteFile(File excelFile) {
excelFile.delete();
}
//如果目录不存在创建目录 存在则不创建
private static void createDir(File file) {
if (!file.exists()) {
file.mkdirs();
}
}
}
StaticUrl
package com.src.common.excel;
import org.springframework.util.ResourceUtils;
import java.io.FileNotFoundException;
/**
* @ProjectName: ycbdqn
* @Package: cn.utils 上传文件路径
* @Author: huat
* @Date: 2020/3/5 13:39
* @Version: 1.0
*/
public class StaticUrl {
public static String getFileUrl(){
String systemPath =null;
try {
systemPath = ResourceUtils.getURL("classpath:").getPath().replace("%20", " ").replace('/', '\\').substring(1);;
/*//从路径字符串中取出工程路径
systemPath=systemPath.substring(0,systemPath.lastIndexOf("Student"));*/
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int result=systemPath.indexOf("\\");
if(-1!=result){
systemPath=systemPath.substring(result).replace("/","\\");
}
return systemPath+"static.excel\\"; //和模板resources下的文件名称一致
// return "E:\IDEA\file\";
}
}
Controller
@RequestMapping("downExcel")
public void downExecl(){
Map<String,Object> map=new HashMap<String,Object>();
map.put("name","学生信息表");
Student student=new Student(123,"张三");
Student student1=new Student(124,"李四");
Student student2=new Student(125,"王五");
List<Student> list=new ArrayList<>();
list.add(student);list.add(student1);list.add(student2);
map.put("studentList",list);
//获取学生信息
//"classpath:static/excel/学生表格.xls" 表格模板保存路径,classpath:代表resources路径
System.out.println(StaticUrl.getFileUrl()+"学生表格.xls");
ExcelUtiles.outExcel(map,response,"学生信息", StaticUrl.getFileUrl()+"学生表格.xls");
}
参考:https://my.oschina.net/u/3535099/blog/4268971