当前位置:   article > 正文

springboot上传excel文件和下载excel(读取mysql表中数据,返回给前端excel文件)_springboot 向前端反馈一个excel

springboot 向前端反馈一个excel

注意事项:上传文件大小限制(不设置的话,文件超过1M会报错):

  1. spring:
  2. #数据源
  3. datasource:
  4. url: jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&useSSL=true
  5. username: root
  6. password: 123456
  7. driver-class-name: com.mysql.cj.jdbc.Driver
  8. servlet:
  9. multipart:
  10. # 最大文件大小。值可以使用后缀“MB”或“KB”。指示兆字节或千字节大小。
  11. max-file-size: 20MB
  12. # # 最大请求大小可以是mb也可以是kb
  13. max-request-size: 200MB

1.上传excel文件,保存在硬盘中:

  1. /**
  2. * 实现文件上传
  3. * */
  4. @RequestMapping("fileUpload")
  5. @ResponseBody
  6. public String fileUpload(@RequestParam("fileName") MultipartFile file){
  7. if(file.isEmpty()){
  8. return "false";
  9. }
  10. String fileName = file.getOriginalFilename();
  11. int size = (int) file.getSize();
  12. System.out.println(fileName + "-->" + size);
  13. String path = "F:/test" ;
  14. File dest = new File(path + "/" + fileName);
  15. if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
  16. dest.getParentFile().mkdir();
  17. }
  18. try {
  19. file.transferTo(dest); //保存文件
  20. return "true";
  21. } catch (IllegalStateException e) {
  22. // TODO Auto-generated catch block
  23. e.printStackTrace();
  24. return "false";
  25. } catch (IOException e) {
  26. // TODO Auto-generated catch block
  27. e.printStackTrace();
  28. return "false";
  29. }
  30. }

2.上传excel文件。保存在硬盘中,并且保证该目录只有一份相同名字的文件。

文件工具类

  1. import org.apache.commons.logging.Log;
  2. import org.apache.commons.logging.LogFactory;
  3. import org.springframework.web.multipart.MultipartFile;
  4. import javax.servlet.http.HttpServletResponse;
  5. import java.io.*;
  6. /**
  7. * @description: 文件上传下载
  8. * @author: Administrator
  9. * @date: 2019-05-31 11:15
  10. */
  11. public class FileAdminUtils {
  12. public static Log log = LogFactory.getLog(ExcelUtil.class);
  13. private static String filePath="G:/test";
  14. public static String multifileUpload(MultipartFile file,String newFileName){
  15. if(file.isEmpty()){
  16. return "false";
  17. }
  18. // String fileName = file.getOriginalFilename();
  19. int size = (int) file.getSize();
  20. log.info("文件名字=="+newFileName+"==文件大小=="+size);
  21. // log.info("文件名字=="fileName + "-->" + size);
  22. String path = filePath;
  23. File dest = new File(path + "/" + newFileName);
  24. if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
  25. dest.getParentFile().mkdir();
  26. }
  27. try {
  28. //保存前先删除重复文件
  29. String del_result=delFile(newFileName);
  30. log.info("删除结果=="+del_result);
  31. file.transferTo(dest); //保存文件
  32. return "true";
  33. } catch (IllegalStateException e) {
  34. // TODO Auto-generated catch block
  35. e.printStackTrace();
  36. return "false";
  37. } catch (IOException e) {
  38. // TODO Auto-generated catch block
  39. e.printStackTrace();
  40. return "false";
  41. }
  42. }
  43. // 删除文件
  44. public static String delFile(String fileName) {
  45. String resultInfo=null;
  46. String sb=filePath+"/"+fileName;
  47. File file = new File(sb);
  48. if (file.exists()) {
  49. if (file.delete()) {
  50. resultInfo = "1-删除成功";
  51. } else {
  52. resultInfo = "0-删除失败";
  53. }
  54. } else {
  55. resultInfo = "文件不存在!";
  56. }
  57. return resultInfo;
  58. }
  59. //文件下载
  60. public static String downLoad(HttpServletResponse response,String filename){
  61. File file = new File(filePath + "/" + filename);
  62. if(file.exists()){ //判断文件父目录是否存在
  63. response.setContentType("application/vnd.ms-excel;charset=UTF-8");
  64. response.setCharacterEncoding("UTF-8");
  65. // response.setContentType("application/force-download");
  66. try {
  67. response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(filename,"UTF-8"));
  68. } catch (UnsupportedEncodingException e) {
  69. e.printStackTrace();
  70. }
  71. byte[] buffer = new byte[1024];
  72. FileInputStream fis = null; //文件输入流
  73. BufferedInputStream bis = null;
  74. OutputStream os = null; //输出流
  75. try {
  76. os = response.getOutputStream();
  77. fis = new FileInputStream(file);
  78. bis = new BufferedInputStream(fis);
  79. int i = bis.read(buffer);
  80. while(i != -1){
  81. os.write(buffer);
  82. i = bis.read(buffer);
  83. }
  84. } catch (Exception e) {
  85. // TODO Auto-generated catch block
  86. e.printStackTrace();
  87. }
  88. System.out.println("----------file download---" + filename);
  89. try {
  90. bis.close();
  91. fis.close();
  92. } catch (IOException e) {
  93. // TODO Auto-generated catch block
  94. e.printStackTrace();
  95. }
  96. }
  97. return null;
  98. }
  99. }

上传测试:

  1. //上传excel表
  2. @PostMapping("/upload")
  3. public String upload(MultipartFile file) {
String newfileName="test.xls";//保存的文件名字
String result= FileAdminUtils.multifileUpload(file,newfileName);
System.out.println("保存文件结果=="+result);
  1. return result;
  2. }

3.下载excel文件:

  1. @RequestMapping("/down")
  2. public String downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
  3. return FileAdminUtils.downLoad(response,"test.xls");
  4. }

web调用下载接口:

window.open("http://xxxx/down?");

4.查询表中的数据,返回给前端excel:

  1. @RequestMapping("/test")
  2. public void downAll(HttpServletResponse response,String id) throws IOException {
  3. List<List<String>> excelData = new ArrayList<>();
  4. List<String> head = new ArrayList<>();
  5. head.add("ID");
  6. head.add("部门");
  7. head.add("名字");
  8. excelData.add(head);
  9. //查询表中的数据
  10. List<MyData> myDatas=myService.list();
  11. log.info("==有"+myDatas.size()+"条数据");
  12. if (myDatas.size()>0){
  13. for (int i=0;i<myDatas.size();i++){
  14. MyData myData=myDatas.get(i);
  15. List<String> data = new ArrayList<>();
  16. data.add(myData.getId());
  17. data.add(myData.getDp());
  18. data.add(myData.getName());
  19. excelData.add(data);
  20. }
  21. }
  22. String sheetName = "sheet表";
  23. String fileName = "test.xls";
  24. // log.info("导出全部excel表");
  25. ExcelOutUtils.exportExcel(response, excelData, sheetName, fileName, 15);
  26. log.info("导出全部excel表成功");
  27. }

excel工具类:

  1. import org.apache.commons.logging.Log;
  2. import org.apache.commons.logging.LogFactory;
  3. import org.apache.poi.hssf.usermodel.*;
  4. import javax.servlet.http.HttpServletResponse;
  5. import java.io.IOException;
  6. import java.util.List;
  7. /**
  8. * @description:
  9. * @author: Administrator
  10. * @date: 2019-05-29 14:31
  11. */
  12. public class ExcelOutUtils {
  13. public static Log log = LogFactory.getLog(ExcelOutUtils.class);
  14. /**
  15. * Excel表格导出
  16. * @param response HttpServletResponse对象
  17. * @param excelData Excel表格的数据,封装为List<List<String>>
  18. * @param sheetName sheet的名字
  19. * @param fileName 导出Excel的文件名
  20. * @param columnWidth Excel表格的宽度,建议为15
  21. * @throws IOException 抛IO异常
  22. */
  23. public static void exportExcel(HttpServletResponse response,
  24. List<List<String>> excelData,
  25. String sheetName,
  26. String fileName,
  27. int columnWidth) throws IOException {
  28. //声明一个工作簿
  29. HSSFWorkbook workbook = new HSSFWorkbook();
  30. //生成一个表格,设置表格名称
  31. HSSFSheet sheet = workbook.createSheet(sheetName);
  32. //设置表格列宽度
  33. sheet.setDefaultColumnWidth(columnWidth);
  34. //写入List<List<String>>中的数据
  35. int rowIndex = 0;
  36. for(List<String> data : excelData){
  37. //创建一个row行,然后自增1
  38. HSSFRow row = sheet.createRow(rowIndex++);
  39. //遍历添加本行数据
  40. for (int i = 0; i < data.size(); i++) {
  41. //创建一个单元格
  42. HSSFCell cell = row.createCell(i);
  43. //创建一个内容对象
  44. HSSFRichTextString text = new HSSFRichTextString(data.get(i));
  45. //将内容对象的文字内容写入到单元格中
  46. cell.setCellValue(text);
  47. }
  48. }
  49. //准备将Excel的输出流通过response输出到页面下载
  50. //八进制输出流
  51. response.setContentType("application/octet-stream");
  52. // 告诉浏览器用什么软件可以打开此文件
  53. response.setHeader("content-Type","application/vnd.ms-excel");
  54. //设置导出Excel的名称
  55. response.setHeader("Content-disposition", "attachment;filename=" + fileName);
  56. //刷新缓冲
  57. response.flushBuffer();
  58. log.info("workbook将Excel写入到response的输出流中,供页面下载该Excel文件");
  59. //workbook将Excel写入到response的输出流中,供页面下载该Excel文件
  60. workbook.write(response.getOutputStream());
  61. log.info("关闭workbook");
  62. //关闭workbook
  63. workbook.close();
  64. }
  65. }

web调用:

window.open("http://xxxx/down?id=1");

另一种下载方式:不知道为啥有时候不行,报Resource interpreted as Document but transferred with MIME type application/json ...:

    var $eleForm = $("<form method='get'></form>");
    $eleForm.attr("action",down_all_url);
    //$eleForm.append("<input name='id' type='hidden' value='"+1+"'>");
    //$(document.body).append($eleForm);
    //提交表单,实现下载
    $eleForm.submit();
    console.log("提交表单,实现下载=="); 
    $eleForm.remove();

另外一种导出excel方法(我觉得比较好):https://blog.csdn.net/l1028386804/article/details/79659605

参考了:https://www.jianshu.com/p/be1af489551c

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/842485
推荐阅读
相关标签
  

闽ICP备14008679号