一、准备工作

Java项目: maven项目添加依赖。web项目可以下载该jar包后导入项目

<!-- excel 下载 -->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.12</version>
</dependency>
<dependency><groupId>org.jxls</groupId><artifactId>jxls-poi</artifactId><version>1.0.9</version>
</dependency>

二、java 工具类


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<Map<String, Object>> list, String[] keys, String columnNames[]) {// 创建excel工作簿Workbook wb = new HSSFWorkbook();// 创建第一个sheet(页),并命名Sheet sheet = wb.createSheet(list.get(0).get("sheetName").toString());// 手动设置列宽。第一个参数表示要为第几列设;,第二个参数表示列的宽度,n为列高的像素数。for (int i = 0; i < keys.length; i++) {sheet.setColumnWidth((short) i, (short) (35.7 * 150));}// 创建第一行Row row = sheet.createRow((short) 0);// 创建两种单元格格式CellStyle cs = wb.createCellStyle();CellStyle cs2 = wb.createCellStyle();// 创建两种字体Font f = wb.createFont();Font f2 = wb.createFont();// 创建第一种字体样式(用于列名)f.setFontHeightInPoints((short) 10);f.setColor(IndexedColors.BLACK.getIndex());f.setBoldweight(Font.BOLDWEIGHT_BOLD);// 创建第二种字体样式(用于值)f2.setFontHeightInPoints((short) 10);f2.setColor(IndexedColors.BLACK.getIndex());// 设置第一种单元格的样式(用于列名)cs.setFont(f);cs.setBorderLeft(CellStyle.BORDER_THIN);cs.setBorderRight(CellStyle.BORDER_THIN);cs.setBorderTop(CellStyle.BORDER_THIN);cs.setBorderBottom(CellStyle.BORDER_THIN);cs.setAlignment(CellStyle.ALIGN_CENTER);// 设置第二种单元格的样式(用于值)cs2.setFont(f2);cs2.setBorderLeft(CellStyle.BORDER_THIN);cs2.setBorderRight(CellStyle.BORDER_THIN);cs2.setBorderTop(CellStyle.BORDER_THIN);cs2.setBorderBottom(CellStyle.BORDER_THIN);cs2.setAlignment(CellStyle.ALIGN_CENTER);// 设置列名for (int i = 0; i < columnNames.length; i++) {Cell cell = row.createCell(i);cell.setCellValue(columnNames[i]);cell.setCellStyle(cs);}// 设置每行每列的值for (short i = 1; i < list.size(); i++) {// Row 行,Cell 方格 , Row 和 Cell 都是从0开始计数的// 创建一行,在页sheet上Row row1 = sheet.createRow(i);// 在row行上创建一个方格for (short j = 0; j < keys.length; j++) {Cell cell = row1.createCell(j);cell.setCellValue(list.get(i).get(keys[j]) == null ? " " : list.get(i).get(keys[j]).toString());cell.setCellStyle(cs2);}}return wb;}public static List<Map<String, Object>> createExcelRecord(String sheetName) {List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();Map<String, Object> map = new HashMap<String, Object>();map.put("sheetName", sheetName);listmap.add(map);return listmap;}/** 新疆空白excel文件*/public static Workbook createEmptyWorkBook() {Workbook wb = new HSSFWorkbook();return wb;}/*** 新建只有列名的表* * @param workbook* @param tatleSheetName 表名* @param columnNames    列名* @return*/public static Workbook createSheet(Workbook workbook, String sheetName, String[] columnNames) {Sheet sheet = workbook.createSheet(sheetName);// 创建第一行Row row = sheet.createRow((short) 0);// 设置列名for (int i = 0; i < columnNames.length; i++) {sheet.setColumnWidth(i, 256 * 20 + 184);Cell cell = row.createCell(i);cell.setCellValue(columnNames[i]);cell.setCellStyle(getColHeadStyle(workbook));}return workbook;}/*** 根据key值将数据填入excel表格* * @param workbook 输出的excel* @param datas    数据* @param colMap   key值* @return*/public static Workbook insertData(Workbook workbook, List<Map<String, Object>> datas, String[] colMap,String sheetName) {Sheet sheet = workbook.getSheet(sheetName);for (int i = 0; i < datas.size(); i++) {Map<String, Object> data = datas.get(i);Row row = sheet.createRow((i + 1));for (int j = 0; j < colMap.length; j++) {Cell cell = row.createCell(j);cell.setCellValue(data.get(colMap[j]) + "");cell.setCellStyle(getColDataStyle(workbook));}}return workbook;}/*** 内容表格样式* * @param workbook* @return*/private static CellStyle getColDataStyle(Workbook workbook) {CellStyle cs2 = workbook.createCellStyle();Font f2 = workbook.createFont();f2.setFontHeightInPoints((short) 14);f2.setColor(IndexedColors.BLACK.getIndex());cs2.setFont(f2);cs2.setBorderLeft(CellStyle.BORDER_THIN);cs2.setBorderRight(CellStyle.BORDER_THIN);cs2.setBorderTop(CellStyle.BORDER_THIN);cs2.setBorderBottom(CellStyle.BORDER_THIN);cs2.setAlignment(CellStyle.ALIGN_CENTER);return cs2;}/*** 第一行表格样式*/private static CellStyle getColHeadStyle(Workbook workbook) {CellStyle cs = workbook.createCellStyle();Font f = workbook.createFont();f.setFontHeightInPoints((short) 11);cs.setFont(f);cs.setBorderLeft(CellStyle.BORDER_THIN);cs.setBorderRight(CellStyle.BORDER_THIN);cs.setBorderTop(CellStyle.BORDER_THIN);cs.setBorderBottom(CellStyle.BORDER_THIN);cs.setAlignment(CellStyle.ALIGN_CENTER);return cs;}/*** * @param contentMaps 数据内容* @param keyNames 内容的key值* @param colNames   列名* @param sheetName  表名* @return*/public static XSSFWorkbook createXssfWb(Map<String, Object>[] contentMaps, List<String> keyNames,List<String> colNames, String sheetName) {XSSFWorkbook book = new XSSFWorkbook();XSSFSheet sheet = book.createSheet(sheetName);// 列名sheet = createXsheetHeader(book, sheet, colNames);// 内容sheet = createXsheetContent(book, sheet, contentMaps, keyNames);return book;}private static XSSFSheet createXsheetContent(XSSFWorkbook book, XSSFSheet sheet, Map<String, Object>[] contentMaps,List<String> keyNames) {if(keyNames == null || keyNames.size() < 1 || contentMaps == null || contentMaps.length < 1) {return sheet;}for(int i=0; i<contentMaps.length; i++) {XSSFRow row = sheet.createRow((i+1));Map<String, Object> map = contentMaps[i];for (String key : map.keySet()) {for(int j=0; j<keyNames.size(); j++) {if(keyNames.get(j).equalsIgnoreCase(key)) {XSSFCell cell = row.createCell(j);if(map.get(key) == null){cell.setCellValue("");}else {cell.setCellValue(map.get(key).toString());}cell.setCellStyle(getXstyleContent(book));break;}}}}/** 合并单元格, 数据为第一个cell 的数据* CellRangeAddress region = new CellRangeAddress(1, 2, 0, 0);  // startRow, endRow, startCol, endCol。起始行,结束行,起始列,结束列* sheet.addMergedRegion(region);*/return null;}private static XSSFSheet createXsheetHeader(XSSFWorkbook book, XSSFSheet sheet, List<String> colNames) {if(colNames == null) {return sheet;}XSSFRow row = sheet.createRow(0);for(int i=0; i<colNames.size(); i++) {String name = colNames.get(i);int length = name.length();sheet.setColumnWidth(i, 256*3*length); XSSFCell cell = row.createCell(i);cell.setCellValue(name);cell.setCellStyle(getXstyleHeader(book));}/* * 合并表头* CellRangeAddress region = new CellRangeAddress(0, 0, 0, 1); // startRow, endRow, startCol, endCol。起始行,结束行,起始列,结束列 * sheet.addMergedRegion(region);*/return sheet;}private static CellStyle getXstyleHeader(XSSFWorkbook book) {XSSFCellStyle contentStyle = book.createCellStyle();// 内容字体样式XSSFFont contFont = book.createFont();// 加粗contFont.setBold(true);// 字体名称contFont.setFontName("楷体");// 字体大小contFont.setFontHeight(13);// 设置字体csscontentStyle.setFont(contFont);// 竖向居中contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 横向居中contentStyle.setAlignment(HorizontalAlignment.CENTER);// 边框contentStyle.setBorderBottom(BorderStyle.THIN);contentStyle.setBorderLeft(BorderStyle.THIN);contentStyle.setBorderRight(BorderStyle.THIN);contentStyle.setBorderTop(BorderStyle.THIN);return contentStyle;}private static CellStyle getXstyleContent(XSSFWorkbook book) {XSSFCellStyle contentStyle = book.createCellStyle();// 内容字体样式XSSFFont contFont = book.createFont();// 加粗contFont.setBold(false);// 字体名称contFont.setFontName("楷体");// 字体大小contFont.setFontHeight(12);// 设置字体csscontentStyle.setFont(contFont);// 横向居中contentStyle.setAlignment(HorizontalAlignment.CENTER);// 边框contentStyle.setBorderBottom(BorderStyle.THIN);contentStyle.setBorderLeft(BorderStyle.THIN);contentStyle.setBorderRight(BorderStyle.THIN);contentStyle.setBorderTop(BorderStyle.THIN);return contentStyle;}// 下载到电脑public void downloadToLocalExcel(String filePath, String fileName, XSSFWorkbook book) {if(StringUtils.isEmptyAll(filePath)) {filePath = this.filePath;}File file = new File(filePath);if(!file.exists()) {file.mkdirs();}FileOutputStream os = null;try {os = new FileOutputStream(filePath + fileName + ".xlsx");  // 文件夹名称叫text.xlsbook.write(os);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (os != null) os.close();} catch (IOException e) {e.printStackTrace();}}}}

三、下载到本地

1.springboot 测试:或者直接调用downloadExcelAndMail 方法


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 {@Testpublic void downloadExcelAndMail() {String filePath = "D:/excel2/";//主题String fileName = "来了,小老弟";String sheetName = "重分配记录明细";// keyList<String> 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<String> headerNames = new ArrayList<>();headerNames.add("重命名时间");headerNames.add("重命名备注");headerNames.add("原名称");headerNames.add("新名称");headerNames.add("操作者");headerNames.add("病历编号");headerNames.add("女方姓名");headerNames.add("男方姓名");// 内容Map<String, Object>[] contentMaps = new HashMap[2];Map<String, Object> map = new HashMap<String, Object>();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<String, Object>();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);}}

2.使用浏览器下载,使用HttpServletResponse

原理:后端处理数据,生成文件。在将文件传输到前端下载。(常用方法)


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})@ResponseBodypublic 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);// keyList<String> 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<String> headerNames = new ArrayList<>();headerNames.add("重命名时间");headerNames.add("重命名备注");headerNames.add("原名称");headerNames.add("新名称");headerNames.add("操作者");headerNames.add("病历编号");headerNames.add("女方姓名");headerNames.add("男方姓名");// 内容Map<String, Object>[] contentMaps = new HashMap[2];Map<String, Object> map = new HashMap<String, Object>();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<String, Object>();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);}}

三、前端请求接口,axios 为例

 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 是啥么鬼??

Java 下载 Excel(.xlsx) 文档相关推荐

  1. 关于GUI_DOWNLOAD中下载excel等文档的乱码问题

    1   GUI_DOWNLOAD 1.1      问题表现 GUI_DOWNLOAD在应用当中有时会导致输出的文件在某些电脑正常显示,在某些电脑乱码显示.这个固然是由于各个电脑系统配置有差异,但是我 ...

  2. 下载图片,文档,excel导入导出

    Q1:下载图片,文档 --1:Fileio.html <!DOCTYPE html> <html> <head> <meta charset="UT ...

  3. 【Java wrod文档导出 返回浏览器下载读取word文档】文档流转IO流

    在工作当中会有很多奇奇怪怪的需求 比如把数据库数据 导出word文档,在此之前发表过一篇 导出ecxle表格的文章,经过查询资料 发现还是很容易实现的 . 我们一共可以分为两个部分 一.把数据库的数据 ...

  4. vue下载xlsx文档流(导出功能)

    一.记录一次前端下载xlsx文档流: 思路: 1. 调用接口接受后台返回的文档流资源, 2.通过内置对象Blob构造器进行解析得到链接地址 3.通过a标签的下载功能得到资源 说下中间踩得坑, 首先项目 ...

  5. java官网下载离线api文档地址

    java官网下载离线api文档地址 看到很多人在csdn资源区放着自己下载过的jdk和java离线文档,很是气愤,很多人只是没找到官网的下载位置,这种免费的东西你也好意思收50C币,甚至有的还要钱,这 ...

  6. java导出生成word文档并进行下载的方法

    前端html内容展示 <div class="col-md-1 col_top_daochu">导出内容并进行下载 </div> 前端js内容展示 < ...

  7. Java EE 、Java SE API帮助文档 中文、英文 下载

    发现要找合适的可下载的API文档 还是比较麻烦的,于是花了点时间在网上找了一些,方便看到这个帖子的各位一次性下载. 内容如下: 注:部分中文翻译可能不太好,自己看看能不能接受,不好的话再找找. 链接: ...

  8. java pdf_Java 生成 PDF 文档

    最近项目需要实现PDF下载的功能,由于没有这方面的经验,从网上花了很长时间才找到相关的资料.整理之后,发现有如下几个框架可以实现这个功能. 1. 开源框架支持 iText,生成PDF文档,还支持将XM ...

  9. Java基于springmvc实现文档预览(openoffice+swftools+flexpaper)(排坑记录)

    Java基于springmvc实现文档预览(openoffice+swftools+flexpaper)(排坑记录) 本文代码来源已在末尾标注,写本文的目的在于记录自己在实践过程中遇到的问题及解决方案 ...

  10. html画布显示PPT,【Web前端问题】有没有办法让HTML5 canvas显示/预览word/excel/powerpoint 文档?...

    目前想实现类似百度文库那样的在线文档预览,但是他们使用的一般都是Flash,而HTML5 canvas可以在大多数情况下代替Flash,那么有没有办法让canvas显示/预览Office文档? 如果不 ...

最新文章

  1. 论排列组合,持续更新
  2. 视频监控软件 SecuritySpy 简介
  3. 行人检测资源综述文献
  4. VS2010中不可忽视的部分——VSTO
  5. SpringMVC 刷课笔记
  6. 总结oninput、onchange与onpropertychange事件的用法和区别
  7. Android HID触摸屏驱动怎么开发
  8. JAVA实现简单电话簿功能
  9. c语言公交查询系统,公交路线查询系统(基于数据结构和C语言)完整
  10. c fread 快读 详解_热量计算公式及例题详解
  11. 混沌初开:全新HarmonyOS 2正式到来!
  12. 满分作文生成器:生活在代码上
  13. 苹果手机怎样录屏 如何录制手机内容
  14. 几种常用的power bi 图表怎么做
  15. kuka机器人焊接编程入门教程_焊接机器人操作编程与应用教学.pptx
  16. day52 css选择器和特性
  17. 新月,上弦月,满月,下弦月的区别
  18. Dell Inspiration 15 7560 增加内存条手把手教学
  19. 关于Ubuntu18.04安装后没有gcc、make、网卡驱动的问题总结以及解决办法
  20. 爬虫初探:把豆瓣读书主页上书的URL、书名、作者、出版时间、出版社全部爬下来

热门文章

  1. 12个Python超强学习网站
  2. java集合类(List+泛型)
  3. 诗词浅析(一)(吾之愚见)
  4. iptables防火墙(二)——SNAT和DNAT
  5. 层次分析法 方案层判断矩阵阶数不同解决方案
  6. 如何安装python安装包
  7. 2021年9月电子学会图形化三级编程题解析含答案:绘制图形
  8. Go Web开发扩展项-GROM框架
  9. C#去除文件夹只读属性
  10. 细数 List 的10个坑,保证你一定遇到过