表格的导出

前端生成表格,导出 excel

import { exportExcel } from 'xlsx-oc';   // 下载包 xlsx-oc ,并且引用
const head = [
  { k: 'name', v: '名称' }, 
  { k: 'age', v: '年龄' }, 
  { k: 'sex', v: '性别' }, 
]
const data = [
  name: 'liu',
  age: 23,
  sex: 'man',
]
const fileName = '个人信息'
exportExcel(head, data, fileName)  // 参数:表头,数据,文件名称

后端生成表格,前端 excel

第一步,获取数据接口,获取 file_token

// page/JMontlyReport.js 
dispatch({
  type: 'JMontlyReport/fetchExportData',
  payload: {
    type: 'website',
    start,
    end,
  },
});

// model/JMontlyReport.js 
*fetchExportData({ payload }, { call, put }) {
  const res = yield call(getCheckData, payload);
  yield put({
    type: 'saveFileToken',
    payload: res,
  });
},
saveFileToken(state, { payload }) {
  return {
    ...state,
    file_token: payload,
  };
},
 
// service/api.js   
export async function getCheckData(params) {
  return request(`/api/monthly_report/export?${stringify(params)}`, {
    method: 'GET',
  });
}

第二部,下载接口,与 file_token 拼接成 url

// page
@connect(state => ({
  fileInfo: state.JMontlyReport.file_token,
}))
const { fileInfo } = this.props;
if (fileInfo) {
  const url = `/api/download-excel/${fileInfo.file_token}?filename="月度经营报表(站点)"`;
  downloadFile(url);
}

// utils/utils
export function downloadFile(url) {
  const aLink = document.createElement('a');  // 创建 <a></a> 链接
  aLink.style.display = 'none';
  aLink.href = url;
  aLink.target = 'blank';

  document.body.appendChild(aLink);
  aLink.click();  // 点击链接
  document.body.removeChild(aLink); // 点击完成,删除 element
}  // 此方法用于下载表格
发布了23 篇原创文章 · 获赞 0 · 访问量 556

猜你喜欢

转载自blog.csdn.net/JIANLI0123/article/details/104542499