js 导出 excel
文章目录
- 简介
- 一、js 文件
- 1、在线引入 js
- 2、Blob 对象
- 3、MIME 类型
- 4、URL对象
- 5、HTML `<a>` 标签的 download 属性
- 6、js 代码
- 二、java 接口
- 1、apache-poi
- 2、easyExcel
- 3、uto-poi、autopoi-web
- 4、文件下载
- 三、测试
简介
文章不是真正的 excel 导出,正常的导出应该是前端展示表格数据,通过点击导出按钮,将表格数据传递给后端,后端接受数据生成 excel 文件通过文件流传递前端,点击确定保存文件。文章 html 缺少表格数据展示,后端缺少 excel 文件生成,通过后端读取本地 excel 流返回前端导出。
一、js 文件
1、在线引入 js
在线引入 axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
或
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
在线引入 jquery Ajax
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.js"></script>
2、Blob 对象
Blob 详解 可参考 https://blog.csdn.net/weixin_43294560/article/details/122086307
Blob(Binary Large Object)表示二进制类型的大对象,File 对象是特殊类型的 Blob
构造函数:
var blob = new Blob([一个由 ArrayBuffer,ArrayBufferView,Blob,DOMString 等对象构成的数组],
{
type:它代表了将会被放入到 blob 中的数组内容的 MIME 类型
endings:
"native",代表行结束符会被更改为适合宿主操作系统文件系统的换行符
"transparent",代表会保持 blob 中保存的结束符不变。
}
);
其中 type 是 MIME 类型,如果不指定默认 text/plain
3、MIME 类型
可参考百度百科 MIME 类型大全:https://baike.baidu.com/item/MIME/2900607?fr=aladdin
常用的类型:
文件后缀 | MIME 类型 |
---|---|
.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对象
- 创建一个新的对象 URL,该对象 URL 可以代表某一个指定的 File 对象或 Blob 对象.
- data 参数是一个 File 对象或者 Blob 对象.
- objectURL 是生成的对象 URL.通过这个 URL,可以获取到所指定文件的完整内容.
- 在你不需要这些对象 URL 的时候,你应该通过调用 window.URL.revokeObjectURL() 方法来释放它们所占用的内容.虽然即使你不主动释放它们,浏览 器也会在当前文档被卸载的时候替你释放,不过,考虑到更好的性能和更少的内存占用,你应该在安全的时候主动施放它们.
5、HTML <a>
标签的 download 属性
-
实例
download 属性具有同源策略,若是不同源不会下载而是跳转
- 打开链接
<a href="http://42.193.0.90:8080/static/picture/bea.jpg" download="bea">
- 下载链接
<a href="/images/myw3schoolimage.jpg" download="w3logo">
-
定义和用法
- 在
<a>
标签中必须设置 href 属性。 - download 指定下载文件的名,如果未带后缀名,则浏览器将自动检测正确的文件扩展名并添加到文件 (.img, .pdf, .txt, .html, 等等)。
- download 属性具有同源策略,若是不同源不会下载而是跳转!
- 在
-
浏览器支持
只有 Firefox 和 Chrome 支持 download 属性。
在 HTML5 中,download 属性是 <a>
标签的新属性。<a download="filename">
filename 用来作为文件名。
6、js 代码
<!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",
// 默认 jQuery 的 ajax 对象中的 dataType 只支持 xml、html、script、json、jsonp、text,不支持 blob
// 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>
二、java 接口
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
官方文档: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
官方文档:https://github.com/jeecgboot/autopoi
autopoi-web
<dependency>
<groupId>org.jeecgframework</groupId>
<artifactId>autopoi-web</artifactId>
<version>1.4.3</version>
</dependency>
auto-poi
<dependency>
<groupId>org.jeecgframework</groupId>
<artifactId>autopoi</artifactId>
<version>1.4.3</version>
</dependency>
4、文件下载
@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();
}
}
三、测试
-
本地文件 -------->
学生信息.xls
-
html 页面
-
下载图片
- 下载成功
- 下载成功
-
点击导出按钮
- 导出成功
- 导出成功