Export table

Front-end to generate tables, export 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)  // 参数:表头,数据,文件名称

Generate a table rear end, the front end excel

The first step to get data interface, access 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',
  });
}

The second part, download interface, with file_token spliced ​​into 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
}  // 此方法用于下载表格
Published 23 original articles · won praise 0 · Views 556

Guess you like

Origin blog.csdn.net/JIANLI0123/article/details/104542499