1.安装组件:cnpm install xlsx --save
2.新建一个辅助ts、js文件 我的excelUtil.ts 注意:新版本的插件导入写法变了:import * as XLSX from 'xlsx'
import { timestampToDateString } from '@/common/dateUtil'
import * as XLSX from 'xlsx'

//headerColumns:属性列表
//headerNames:属性名称列表,要和headerColumns顺序一致。
//dateColumns:headerColumns中要从long转换为date的列集合
//dataTable:数据源
//fileName:导出的excel文件名称
export function exportExcel(headerColumns: string[], headerNames: string[], dateColumns: string[], dataArr: any, fileName: string) {
    //复制一个新数组出来,不能操作原数组。
    // let dataArr = dataTable.slice();
    //要导出的数据
    let dataArrExport = [];
    for (let k = 0; k < dataArr.length; k++) {
        let itemArr = [];
        let dataItem = dataArr[k];
        for (let m = 0; m < headerColumns.length; m++) {
            let key = headerColumns[m];
            if (dataItem.hasOwnProperty(key)) {
                // 对象具有该属性
                let v = dataItem[key] + '';
                //日期要转换
                if (dateColumns.indexOf(key) > -1) {
                    v = timestampToDateString(parseInt(v));
                }
                itemArr.push(v);
            } else {
                // 对象不具有该属性
                itemArr.push('');
            }
        }
        dataArrExport.push(itemArr);
    }
    dataArrExport.unshift(headerNames);//在开端添加一个元素 表头
    const ws = XLSX.utils.aoa_to_sheet(dataArrExport);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    XLSX.writeFile(wb, fileName);
}

日期辅助dateUtil.js

//日期戳转日期字符串:yyyy-MM-dd HH:mm:ss
export const timestampToDateString = (v: number) => {
    if (v == null) {
        return '';
    } else {
        const dateObj = new Date(v); // 创建Date对象
        const year = dateObj.getFullYear(); // 获取年份
        const month = ("0" + (dateObj.getMonth() + 1)).slice(-2); // 获取月份,并补零
        const day = ("0" + dateObj.getDate()).slice(-2); // 获取日期,并补零
        const hour = ("0" + dateObj.getHours()).slice(-2); // 获取小时,并补零
        const minute = ("0" + dateObj.getMinutes()).slice(-2); // 获取分钟,并补零
        const second = ("0" + dateObj.getSeconds()).slice(-2); // 获取秒,并补零
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`; // 返回转换后的日期格式
    }
}

export const timestampToDateShortString = (v: number) => {
    let fullDateStr = timestampToDateString(v);
    if(fullDateStr != ''){
        fullDateStr = fullDateStr.substring(0,11);
    }
    return fullDateStr;
}

//获取时间戳
export function getNowTimeSpan() {
    return new Date().getTime();//.toString()
}

//获取时间戳
export function getDateTimeSpan(date: Date) {
    return date.getTime();//.toString()
}

页面上面的用法

import { exportExcel } from '@/common/excelUtil'
import { getNowTimeSpan, timestampToDateShortString } from '@/common/dateUtil'

const TestExport = () => {
  let timeStamp = getNowTimeSpan();
  let shortDate = timestampToDateShortString(timeStamp);
  let headerColumns = ['name', 'age', 'city', 'birth'];//列字段
  let headerNames = ['姓名', '年龄', '城市', '生日'];//列名称
  let dateColumns = ['birth'];//需要转换为日期的列
  //数据源
  let dataArr = [
    { name: "John", age: 30, city: "New York", birth: timeStamp },
    { name: "Alice", age: 25, city: "Los Angeles", birth: timeStamp },
    { name: "Bob", age: 35, city: "Chicago", birth: timeStamp }
  ];
  let fileName = timeStamp + '.xlsx';//导出Excel文件名
  exportExcel(headerColumns, headerNames, dateColumns, dataArr, fileName);
}

 

posted on 2024-06-20 16:20  邢帅杰  阅读(59)  评论(0编辑  收藏  举报