惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
博客园 - 三生石上(FineUI控件)
S
Securelist
U
Unit 42
The Cloudflare Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Simon Willison's Weblog
Simon Willison's Weblog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
B
Blog
T
Tenable Blog
The Hacker News
The Hacker News
The Register - Security
The Register - Security
IT之家
IT之家
博客园 - 【当耐特】
Spread Privacy
Spread Privacy
P
Privacy & Cybersecurity Law Blog
博客园_首页
T
Tailwind CSS Blog
人人都是产品经理
人人都是产品经理
C
Cybersecurity and Infrastructure Security Agency CISA
Know Your Adversary
Know Your Adversary
NISL@THU
NISL@THU
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
T
Tor Project blog
C
CERT Recently Published Vulnerability Notes
Apple Machine Learning Research
Apple Machine Learning Research
Stack Overflow Blog
Stack Overflow Blog
T
Threat Research - Cisco Blogs
T
The Exploit Database - CXSecurity.com
V
Vulnerabilities – Threatpost
A
Arctic Wolf
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
V
V2EX
aimingoo的专栏
aimingoo的专栏
大猫的无限游戏
大猫的无限游戏
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
Cyberwarzone
Cyberwarzone
V
Visual Studio Blog
月光博客
月光博客
爱范儿
爱范儿
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
美团技术团队
G
GRAHAM CLULEY
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
H
Heimdal Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

博客园 - SamDragon

如何通过LangChain实现记忆功能的总结 基于LangChain的Ai应用开发平台 .net CPU和内存爆高的分析与处理01 ApiTemplate:.net后端项目模板完善与总结 Jenkins之Nunit的应用 jenkins发布application且并运行 Jenkins基础系统之完整的.net项目编译 Jenkins基础系统之更换镜像源 记一次业余项目的敏捷开发实践 奉上简单的.Net后端开发模板 C#之委托如此简单 cordova环境搭建 Linux实现免密码登录 ElasticSearch安装及运行的坑 Autofac 应用于IIS托管的WEB程序,注册程序集被回收的问题 通过Thrift实现C#与Hbase交流 OpenLayer实现路径运动 对SVN的落地与实践总结 Jenkins配置从节点
前端导出Excel和打印介绍
SamDragon · 2020-11-29 · via 博客园 - SamDragon

开发后台管理系统时,都需要实现打印、导出Excel这两项功能,在前后台分离的开发模式,你是否想找一个前端解决方案。这样后端开发人员就不用为每个报表功能附加一个导出Excel的接口了,那我们进入主题吧。

核心问题-导出Excel是个麻烦

打印不用多说,前端很容易搞定,因为浏览器自带;主要是导出Excel,因为浏览器没有默认支持,而以前大多数据项目都是后台提供接口生成excel文件后下载。

解决问题-引入两个开源库

  • printa-js

支持丰富内容的打印组件,原名print-js,printa-js是本人fork后加以改动增加了对页底部内容自定义的功能。git地址:https://github.com/cqhaibin/Print.js

  • xlsx

前端导出excel解决方案 git地址:https://github.com/SheetJS/sheetjs

  • npm安装包
npm install --save printa-js xlsx
  • 导入包
import * as printJS from 'printa-js'
import * as XLSX from 'xlsx'

打印与导出JSON的通用代码

打印

/**
 * 普通的打印方法
 * data: 数据
 * columns:列集合
 * title: 标题
 * subTitle: 副标题
 * 数据格式
 * properties: [{filed:'id', displayName: 'title'}]
 * printable: [{ id:1 },{id: 2}]
 * @param opt { printable: datas, properties: columns }
 */
export function printTable ({ data, columns, header, footer }) {
  const props = []
  columns.forEach(c => {
    if (c.ignorePrint) {
      return
    }
    props.push({
      field: c.field,
      displayName: c.label
    })
  })
  const distData = []
  data.forEach(item => {
    const tmp = {}
    columns.forEach(c => {
      if (item[c.field] !== undefined) {
        let val = item[c.field]
        if (c.format) {
          val = c.format(val, item)
        }
        Object.defineProperty(tmp, c.field, {
          value: val || ''
        })
      }
    })
    distData.push(tmp)
  })
  const opt = {
    properties: props,
    printable: distData,
    header: '<div class="header" >' + (header || '') + '</div>',
    style: ' .title { text-align: center; }, .second-title{ font-size:12px; font-weidth: norm; }, .line{ text-decoration: underline; } ',
    type: 'json',
    footer: footer || ''
  }
  printJS(opt)
}

导出Excel

/**
 * 导出excel
 * 数据格式:
 * [
        ['姓名', '年龄', '日期'],
        ['sam', 20, new Date()],
        ['long', 20, new Date()]
   ]
 */
export function excelTable ({ data, columns, title, fName, footer }) {
  const props = []
  columns.forEach(c => {
    if (c.ignorePrint) {
      return
    }
    props.push(c.label)
  })
  const distData = []
  distData.push(props)
  data.forEach(item => {
    const tmp = []
    columns.forEach(c => {
      if (item[c.field] !== undefined) {
        let val = item[c.field]
        if (c.format) {
          val = c.format(val, item)
        }
        tmp.push(val || '')
      } else {

      }
    })
    distData.push(tmp)
  })

  distData.unshift([title])

  const sheet = XLSX.utils.aoa_to_sheet(distData)
  const len = props.length
  sheet['!merges'] = [
    {
      s: {
        c: 0,
        r: 0
      },
      e: {
        c: len,
        r: 0
      }
    }
  ]
  const wb = {
    SheetNames: ['sheet1'],
    Sheets: {}
  }
  wb.Sheets.sheet1 = sheet
  // not support ie
  const fileName = fName || (title + '-' + (new Date()).getTime()) + '.xls'
  XLSX.writeFile(wb, fileName)
}