12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- <template>
- <el-button type="primary" @click="exportToExcel">
- <img src="@/assets/imgs/OA/open.png" class="mr-8px" alt="" />
- 导出
- </el-button>
- </template>
- <script setup lang="ts">
- /**
- * @description 导出为excel
- */
- import * as XLSX from 'xlsx'
- import { saveAs } from 'file-saver'
- interface IProp {
- data: any[][] // 数据 [[表头,表头,表头],[数据,数据,数据]]
- fileName?: string // 文件名
- mergeRanges?: {
- s: { r: number; c: number } // 合并的起始单元格
- e: { r: number; c: number } // 合并的结束单元格
- }[] // 合并单元格列表
- colsWidth?: { wch: number }[] // 列宽
- }
- // 定义组件props
- const props = defineProps<IProp>()
- // 导出Excel函数
- const exportToExcel = () => {
- // 从props获取数据
- const data = props.data
- // 创建一个工作簿
- const wb = XLSX.utils.book_new()
- // 创建一个工作表
- const ws = XLSX.utils.aoa_to_sheet(data)
- // 合并表头的单元格,定义多个合并范围
- ws['!merges'] = props.mergeRanges ?? []
- // 设置列宽,定义多个列宽
- ws['!cols'] = props.colsWidth ?? []
- // 将工作表添加到工作簿中
- XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
- // 生成Excel文件
- const wbout = XLSX.write(wb, { type: 'binary', bookType: 'xlsx' })
- // 下载Excel文件
- saveAs(
- new Blob([s2ab(wbout)], { type: 'application/octet-stream' }),
- props.fileName || 'exported_data.xlsx'
- )
- }
- // 将二进制字符串转换为字节数组
- const s2ab = (s: string) => {
- const buf = new ArrayBuffer(s.length)
- const view = new Uint8Array(buf)
- for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff
- return buf
- }
- </script>
- <style scoped></style>
|