Java项目: maven项目添加依赖。web项目可以下载该jar包后导入项目
org.apache.poi
poi
3.12
org.jxls
jxls-poi
1.0.9
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* 导出Excel文档工具类
*/
public class ExcelUtil {
/**
* 创建excel文档,
*
* @param list 数据
* @param keys list中map的key数组集合
* @param columnNames excel的列名
*/
public static Workbook createWorkBook(List
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.monitor.email.MailService;
import com.monitor.service.ExcelService;
import com.monitor.utils.ExcelUtil;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ExcelDownloadTest {
@Test
public void downloadExcelAndMail() {
String filePath = "D:/excel2/";
//主题
String fileName = "来了,小老弟";
String sheetName = "重分配记录明细";
// key
List keyNames = new ArrayList<>();
keyNames.add("modifyDate");
keyNames.add("notes");
keyNames.add("oldName");
keyNames.add("newName");
keyNames.add("userName");
keyNames.add("casnum");
keyNames.add("womanName");
keyNames.add("manName");
// 列名
List headerNames = new ArrayList<>();
headerNames.add("重命名时间");
headerNames.add("重命名备注");
headerNames.add("原名称");
headerNames.add("新名称");
headerNames.add("操作者");
headerNames.add("病历编号");
headerNames.add("女方姓名");
headerNames.add("男方姓名");
// 内容
Map[] contentMaps = new HashMap[2];
Map map = new HashMap();
map.put("modifyDate", "2019-12-12 10:56:20");
map.put("notes", "notes");
map.put("oldName", "oldName");
map.put("newName","oldName");
map.put("userName", "oldName");
map.put("casnum", "oldName");
map.put("womanName", "oldName");
map.put("manName", "oldName");
contentMaps[0] = map;
map = new HashMap();
map.put("modifyDate", "2019-12-13 10:56:20");
map.put("notes", "notes1");
map.put("oldName", "oldName1");
map.put("newName","oldName1");
map.put("userName", "oldName1");
map.put("casnum", "oldName1");
map.put("womanName", "oldName1");
map.put("manName", "oldName1");
contentMaps[1] = map;
XSSFWorkbook book = ExcelUtil.createXssfWb(contentMaps, keyNames, headerNames, sheetName);
ExcelUtil.downloadToLocalExcel(filePath, fileName, book);
}
}
原理:后端处理数据,生成文件。在将文件传输到前端下载。(常用方法)
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.monitor.utils.ExcelUtil;
@Controller
@RequestMapping("/excelDwn/")
public class ExcelController {
/**
* response 响应浏览器,文件传回前端,使用浏览器下载
* @param response
* @param book
* @throws Exception
*/
public void outputExcel(HttpServletResponse response, XSSFWorkbook book) throws Exception {
OutputStream output = null;
BufferedOutputStream bufferedOutPut = null;
try {
output = response.getOutputStream();
bufferedOutPut = new BufferedOutputStream(output);
// 执行 flush 操作, 将缓存区内的信息更新到文件上
bufferedOutPut.flush();
// 将最新 的 Excel 文件写入到文件输出流中,更新文件信息
book.write(bufferedOutPut);
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (output != null) {
output.close();
}
if (bufferedOutPut != null) {
// 关闭输出流对象
bufferedOutPut.close();
}
}
}
/**
* 设置响应信息
* @param response
* @return
*/
private HttpServletResponse getResponse(HttpServletResponse response) {
// 如果使用该ContentType则浏览器自动下载到默认下载地址
// response.setContentType("application/vnd.ms-excel;charset=UTF-8");
// 如果使用这两行代码则浏览器会弹出另存为的弹窗
response.setHeader("Content-Type", "application/force-download");
response.setContentType("application/x-download;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
return response;
}
/**
* 测试
* @param request
* @param response
* @throws Exception
*/
@RequestMapping(value = "exportRedistributionDetail", method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public void exportRedistributionDetail(HttpServletRequest request, HttpServletResponse response) throws Exception {
String sheetName = "重分配记录明细";
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(("测试文件" + "2019-12-13" + ".xlsx").getBytes("GBK"), "ISO-8859-1")); // 名称
response = getResponse(response);
// key
List keyNames = new ArrayList<>();
keyNames.add("modifyDate");
keyNames.add("notes");
keyNames.add("oldName");
keyNames.add("newName");
keyNames.add("userName");
keyNames.add("casnum");
keyNames.add("womanName");
keyNames.add("manName");
// 列名
List headerNames = new ArrayList<>();
headerNames.add("重命名时间");
headerNames.add("重命名备注");
headerNames.add("原名称");
headerNames.add("新名称");
headerNames.add("操作者");
headerNames.add("病历编号");
headerNames.add("女方姓名");
headerNames.add("男方姓名");
// 内容
Map[] contentMaps = new HashMap[2];
Map map = new HashMap();
map.put("modifyDate", "2019-12-12 10:56:20");
map.put("notes", "notes");
map.put("oldName", "oldName");
map.put("newName","oldName");
map.put("userName", "oldName");
map.put("casnum", "oldName");
map.put("womanName", "oldName");
map.put("manName", "oldName");
contentMaps[0] = map;
map = new HashMap();
map.put("modifyDate", "2019-12-13 10:56:20");
map.put("notes", "notes1");
map.put("oldName", "oldName1");
map.put("newName","oldName1");
map.put("userName", "oldName1");
map.put("casnum", "oldName1");
map.put("womanName", "oldName1");
map.put("manName", "oldName1");
contentMaps[1] = map;
XSSFWorkbook book = ExcelUtil.createXssfWb(contentMaps, keyNames, headerNames, sheetName);
// 输出EXCEL IO流数据
outputExcel(response, book);
}
}
Vue.prototype.$axios({
method: 'post',
timeout: 10000,
url: '下载地址',
responseType: 'blob', // 响应类型,必须
data: {
}
}).then(response => {
console.log(response);
// 通过 a 标签创建一个虚拟链接下载文件
var blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' }); // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 这里表示xlsx类型
var downloadElement = document.createElement('a');
var href = window.URL.createObjectURL(blob); // 创建下载的链接
downloadElement.href = href;
downloadElement.download = '文件名'; // 下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); // 点击下载
document.body.removeChild(downloadElement); // 下载完成移除元素
window.URL.revokeObjectURL(href); // 释放掉blob对象
}).catch(function(error) {
console.log(error);
});
responseType: 'blob', // 响应类型,必须 bolb 是啥么鬼??