js export excel

Introduction

文章不是真正的 excel 导出,正常的导出应该是前端展示表格数据,通过点击导出按钮,将表格数据传递给后端,后端接受数据生成 excel 文件通过文件流传递前端,点击确定保存文件。文章 html 缺少表格数据展示,后端缺少 excel 文件生成,通过后端读取本地 excel 流返回前端导出。

1. js file

1. Import js online

Introduce axios online

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

or

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Introduce jquery Ajax online

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
2. Blob object

Blob detailed explanation can refer to https://blog.csdn.net/weixin_43294560/article/details/122086307

Blob (Binary Large Object) represents a large object of binary type, and a File object is a special type of Blob

Constructor:

var blob = new Blob([一个由 ArrayBuffer,ArrayBufferView,Blob,DOMString 等对象构成的数组], 
	{
    
    
		type:它代表了将会被放入到 blob 中的数组内容的 MIME 类型
		endings:
			"native",代表行结束符会被更改为适合宿主操作系统文件系统的换行符
			"transparent",代表会保持 blob 中保存的结束符不变。
	}
);

Where type is the MIME type, if not specified the default text/plain

3. MIME type

You can refer to Baidu Encyclopedia MIME Type Encyclopedia: https://baike.baidu.com/item/MIME/2900607?fr=aladdin

Commonly used types:

File extension MIME type
.txt text/plain
.html text/html
.csv text/csv
.jpeg/.jpg image/jpeg
.png image/png
.rar application/x-rar-compressed
.doc application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.xls application/vnd.ms-excel
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.zip application/zip
4. URL object
  • Create a new object URL, which can represent a specified File object or Blob object.
  • The data parameter is a File object or a Blob object.
  • objectURL is the generated object URL. Through this URL, the complete content of the specified file can be obtained.
  • When you don't need these object URLs, you should call the window.URL.revokeObjectURL() method to release the content they occupy. Although even if you don't actively release them, the browser will replace them when the current document is unloaded. You release, however, considering better performance and less memory usage, you should actively release them when it is safe.
5. <a>The download attribute of the HTML tag
  • example

    The download attribute has the same-origin policy, if the source is different, it will not download but jump

    • open link
    <a href="http://42.193.0.90:8080/static/picture/bea.jpg" download="bea">
    
    • download link
    <a href="/images/myw3schoolimage.jpg" download="w3logo">
    
  • Definition and usage

    • The href attribute must be set in <a>the tag .
    • download Specifies the name of the downloaded file. If there is no extension, the browser will automatically detect the correct file extension and add it to the file (.img, .pdf, .txt, .html, etc.).
    • The download attribute has the same-origin policy, if the source is different, it will not download but jump!
  • Browser Support
    insert image description here
    Only Firefox and Chrome support the download attribute.

In HTML5, the download attribute is a new attribute of <a>the tag . <a download="filename">filename is used as the file name.

6. js code
<!DOCTYPE html>
<!-- lang 作用:浏览器判断默认语言是否和 lang 设置的一致,如果不一致,询问是否翻译(能弹出前提:是你在浏览器设置允许语言不同翻译,一般浏览器默认打开,比如 Google)-->
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>导出 excel</title>
</head>
<body>
<p>使用 a 标签的 download 下载非同源文件---带文件后缀,可以不指定 Blob 对象 MIME 类型</p>
<button onclick="aDownloadAxios('bea.jpg')">axios 下载非同源文件</button>
<p>使用原生 XMLHttpRequest 对象发送 get 请求方式</p>
<button onclick="load('XMLHttpRequest')">XMLHttpRequest 导出</button>
<p>使用 jQuery ajax 发送 get 请求方式</p>
<button onclick="loadAjax('ajax.xls')">ajax 导出-----带文件后缀,不指定 Blob 对象 MIME 类型</button>
<p>使用 axios 发送 get 请求方式</p>
<button onclick="loadAxios('axios')">axios 导出</button>
</body>
</html>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script type="text/javascript">

    function load(fileName) {
      
      
        if (typeof window.navigator.msSaveBlob != 'undefined') {
      
      
            // IE 11 测试成功
            alert("使用 window.navigator 创建 .txt 文件")
            //创建
            const blob = new Blob(["I scream. You scream. We all scream for ice cream."]);
            window.navigator.msSaveBlob(blob, fileName + '.txt'); // 下载
            //window.navigator.msSaveOrOpenBlob(blob, fileName + '.txt'); // 下载和保存
        } else {
      
      
            // Firefox 、Chrome 、Edge 测试成功
            alert("使用 window.URL 创建 .excel 文件")
            var xhr = new XMLHttpRequest();
            xhr.open("get", "http://127.0.0.1:8090/oauth/file/excel", true);
            xhr.responseType = "blob";  //重点:设置接收类型
            xhr.onload = function () {
      
      
                if (this.status == 200) {
      
      
                    var data = this.response;
                    // 创建一个新的对象URL,该对象URL可以代表某一个指定的File对象或Blob对象.
                    // data参数是一个File对象或者Blob对象.
                    // objectURL是生成的对象URL.通过这个URL,可以获取到所指定文件的完整内容.
                    // 在你不需要这些对象URL的时候,你应该通过调用 window.URL.revokeObjectURL()方法来释放它们所占用的内容.虽然即使你不主动释放它们,浏览 器也会在当前文档被卸载的时候替你释放,不过,考虑到更好的性能和更少的内存占用,你应该在安全的时候主动施放它们.
                    const url = window.URL.createObjectURL(new Blob([data], {
      
      
                        type: 'application/vnd.ms-excel',
                        //endings: "transparent"
                    }));
                    const a = document.createElement('a');
                    a.href = url
                    a.setAttribute("download", fileName + '.xls')
                    a.click()
                    window.URL.revokeObjectURL(url)
                }
            }
            xhr.send();
        }
    }

    function loadAjax(fileName) {
      
      
        $.ajax({
      
      
            type: "GET",
            url: "http://127.0.0.1:8090/oauth/file/excel",

			// 请求类型
			// contentType: "application/json",
			
			// 响应类型:默认 jQuery 的 ajax 对象中的 dataType 只支持 xml、html、script、json、jsonp、text,不支持 blob,用 xhrFields 设置
            // dataType: "blob", 错误写法
            // 修改 jQuery 的 ajax 对象中的 xhrFields 属性,定义 responseType 响应类型为 blob (xhrFields: 接受一个key-value对象,透传给原生的XHR)
            xhrFields: {
      
      
                responseType: 'blob'
            },
            success: function (data) {
      
      
                console.log(typeof data)
                const url = window.URL.createObjectURL(new Blob([data]));
                const a = document.createElement('a');
                a.href = url
                a.setAttribute("download", fileName)
                a.click()
                window.URL.revokeObjectURL(url)
            }
        })
    }

    function loadAxios(fileName) {
      
      
        this.axios(
            {
      
      
                url: 'http://127.0.0.1:8090/oauth/file/excel',
                method: 'get',
                params: {
      
      },
                responseType: 'blob'
            }
        ).then((res) => {
      
      
            console.log(res.data)
            if (!res.data) {
      
      
                return
            }
            const url = window.URL.createObjectURL(new Blob([res.data], {
      
      
                type: 'application/vnd.ms-excel',
            }))
            const a = document.createElement('a')
            a.href = url
            a.setAttribute('download', fileName + '.xls')
            a.click()
            window.URL.revokeObjectURL(url)
        })

    }

    function aDownloadAxios(fileName) {
      
      
        this.axios(
            {
      
      
                // 静态资源
                url: 'http://42.193.0.90:8080/static/picture/bea.jpg',
                method: 'get',
                responseType: 'blob'
            }
        ).then((res) => {
      
      
            if (!res.data) {
      
      
                return
            }
            const url = window.URL.createObjectURL(new Blob([res.data]))
            const a = document.createElement('a')
            a.href = url
            a.setAttribute('download', fileName)
            a.click()
            window.URL.revokeObjectURL(url)
        })
    }
</script>

Two, java interface

1、apache-poi
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.2.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.2.2</version>
    </dependency>
2、easyExcel

Official document: https://easyexcel.opensource.alibaba.com/docs/current/

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>easyexcel</artifactId>
        <version>2.2.10</version>
    </dependency>
3、uto-poi、autopoi-web

Official documentation: https://github.com/jeecgboot/autopoi

autopoi-web

	<dependency>
		 <groupId>org.jeecgframework</groupId>
		 <artifactId>autopoi-web</artifactId>
		 <version>1.4.3</version>
	</dependency>

self-then

	<dependency>
	    <groupId>org.jeecgframework</groupId>
	    <artifactId>autopoi</artifactId>
	    <version>1.4.3</version>
	</dependency>
4. File download
@RestController
@RequestMapping("/file")
public class FileExportController {
    
    

    @GetMapping("/excel")
    public void exportExcel(HttpServletResponse response) throws IOException {
    
    
    	// 使用本地 excel 文件,模拟前端传递数据生成的 excel,可使用上面 easyExcel、autopoi-web 封装好的方法生成
        File file = new File("C:\\Users\\Dell\\Desktop\\学生信息.xls");
        FileInputStream fileInputStream = new FileInputStream(file);
        Workbook worKbook = new HSSFWorkbook(fileInputStream);
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), String.valueOf(StandardCharsets.UTF_8)));
        response.setHeader("Access-Control-Allow-Origin", "*");
        //response.setContentType("application/octet-stream;charset=UTF-8");
        //response.setContentType("application/vnd.ms-excel");
        ServletOutputStream outputStream = response.getOutputStream();
        worKbook.write(outputStream);
        outputStream.flush();
        worKbook.close();
    }
}    

3. Test

  • Local file -------->学生信息.xls
    insert image description here

  • html page
    insert image description here

  • download pictures
    insert image description here

    • download successful
      insert image description here
  • Click the export button

    insert image description here

    • Export succeeded
      insert image description here

Guess you like

Origin blog.csdn.net/qq_41538097/article/details/127013304