流文件转码



import FileSaver from 'file-saver'
const Excel = require('exceljs')

export var exportExcel = function (luckysheet, value) {
    // 1.创建工作簿,可以为工作簿添加属性
    const workbook = new Excel.Workbook()
     console.log(workbook);
     console.log(workbook.xlsx.writeBuffer());
    // 2.创建表格,第二个参数可以配置创建什么样的工作表
    luckysheet.forEach(function (table) {
      if (table.data.length === 0) return true
      const worksheet = workbook.addWorksheet(table.name)
      const merge = (table.config && table.config.merge) || {}
      const borderInfo = (table.config && table.config.borderInfo) || {}
      // 3.设置单元格合并,设置单元格边框,设置单元格样式,设置值,导出图片
      setStyleAndValue(table.data, worksheet)
      setMerge(merge, worksheet)
      setBorder(borderInfo, worksheet)
     // setImages(table.images, worksheet, workbook)
      return true
    })
     
    // 4.写入 buffer
    const buffer = workbook.xlsx.writeBuffer().then(data => {
      const blob = new Blob([data], {
        type: 'application/vnd.ms-excel;charset=utf-8'
      })
      console.log('导出成功!')
      FileSaver.saveAs(blob, `${value}.xlsx`);
    //  let file = new window.File([blob],"流文件命名.xlsx",{type:"text/plain"});
    //    return file
    })
    return buffer
  }







var setMerge = function (luckyMerge = {}, worksheet) {
  const mergearr = Object.values(luckyMerge)
  mergearr.forEach(function (elem) {
    // elem格式:{r: 0, c: 0, rs: 1, cs: 2}
    // 按开始行,开始列,结束行,结束列合并(相当于 K10:M12)
    worksheet.mergeCells(
      elem.r + 1,
      elem.c + 1,
      elem.r + elem.rs,
      elem.c + elem.cs
    )
  })
}

var setBorder = function (luckyBorderInfo, worksheet) {
  if (!Array.isArray(luckyBorderInfo)) return
  // console.log('luckyBorderInfo', luckyBorderInfo)
  luckyBorderInfo.forEach(function (elem) {
    // 现在只兼容到borderType 为range的情况
    // console.log('ele', elem)
    if (elem.rangeType === 'range') {
      const border = borderConvert(elem.borderType, elem.style, elem.color)
      const rang = elem.range[0]
      // console.log('range', rang)
      const row = rang.row
      const column = rang.column
      for (let i = row[0] + 1; i < row[1] + 2; i++) {
        for (let y = column[0] + 1; y < column[1] + 2; y++) {
          worksheet.getCell(i, y).border = border
        }
      }
    }
    if (elem.rangeType === 'cell') {
      // col_index: 2
      // row_index: 1
      // b: {
      //   color: '#d0d4e3'
      //   style: 1
      // }
      const { colIndex, rowIndex } = elem.value
      const borderData = Object.assign({}, elem.value)
      delete borderData.col_index
      delete borderData.row_index
      const border = addborderToCell(borderData, rowIndex, colIndex)
      // console.log('bordre', border, borderData)
      worksheet.getCell(rowIndex + 1, colIndex + 1).border = border
    }
    // console.log(rang.column_focus + 1, rang.row_focus + 1)
    // worksheet.getCell(rang.row_focus + 1, rang.column_focus + 1).border = border
  })
}
var setStyleAndValue = function (cellArr, worksheet) {
  if (!Array.isArray(cellArr)) return
  cellArr.forEach(function (row, rowid) {
    row.every(function (cell, columnid) {
      if (!cell) return true
      const fill = fillConvert(cell.bg)

      const font = fontConvert(
        cell.ff,
        cell.fc,
        cell.bl,
        cell.it,
        cell.fs,
        cell.cl,
        cell.ul
      )
      const alignment = alignmentConvert(cell.vt, cell.ht, cell.tb, cell.tr)
      let value = ''

      if (cell.f) {
        value = { formula: cell.f, result: cell.v }
      } else if (!cell.v && cell.ct && cell.ct.s) {
        // xls转为xlsx之后,内部存在不同的格式,都会进到富文本里,即值不存在与cell.v,而是存在于cell.ct.s之后
        // value = cell.ct.s[0].v
        cell.ct.s.forEach(arr => {
          value += arr.v
        })
      } else {
        value = cell.v
      }
      //  style 填入到_value中可以实现填充色
      const letter = createCellPos(columnid)
      const target = worksheet.getCell(letter + (rowid + 1))
      // console.log('1233', letter + (rowid + 1))
      for (const key in fill) {
          target.fill = fill
          console.log(key)
        break
      }
      target.font = font
      target.alignment = alignment
      target.value = value

      return true
    })
  })
}

// var setImages = function (imagesArr, worksheet, workbook) {
//   if (typeof imagesArr !== 'object') return
//   for (const key in imagesArr) {
//     // console.log(imagesArr[key]);
//     // 通过 base64  将图像添加到工作簿
//     const myBase64Image = imagesArr[key].src
//     // 开始行 开始列 结束行 结束列
//     const start = { col: imagesArr[key].fromCol, row: imagesArr[key].fromRow }
//     const end = { col: imagesArr[key].toCol, row: imagesArr[key].toRow }
//     const imageId = workbook.addImage({
//       base64: myBase64Image,
//       extension: 'png'
//     })
//     worksheet.addImage(imageId, {
//       tl: start,
//       br: end,
//       editAs: 'oneCell'
//     })
//   }
// }

var fillConvert = function (bg) {
  if (!bg) {
    return {}
  }
  // const bgc = bg.replace('#', '')
  const fill = {
    type: 'pattern',
    pattern: 'solid',
    fgColor: { argb: bg.replace('#', '') }
  }
  return fill
}

var fontConvert = function (
  ff = 0,
  fc = '#000000',
  bl = 0,
  it = 0,
  fs = 10,
  cl = 0,
  ul = 0
) {
  // luckysheet:ff(样式), fc(颜色), bl(粗体), it(斜体), fs(大小), cl(删除线), ul(下划线)
  const luckyToExcel = {
    0: '微软雅黑',
    1: '宋体(Song)',
    2: '黑体(ST Heiti)',
    3: '楷体(ST Kaiti)',
    4: '仿宋(ST FangSong)',
    5: '新宋体(ST Song)',
    6: '华文新魏',
    7: '华文行楷',
    8: '华文隶书',
    9: 'Arial',
    10: 'Times New Roman ',
    11: 'Tahoma ',
    12: 'Verdana',
    num2bl: function (num) {
      return num !== 0
    }
  }
  // 出现Bug,导入的时候ff为luckyToExcel的val

  const font = {
    name: typeof ff === 'number' ? luckyToExcel[ff] : ff,
    family: 1,
    size: fs,
    color: { argb: fc.replace('#', '') },
    bold: luckyToExcel.num2bl(bl),
    italic: luckyToExcel.num2bl(it),
    underline: luckyToExcel.num2bl(ul),
    strike: luckyToExcel.num2bl(cl)
  }

  return font
}

var alignmentConvert = function (
  vt = 'default',
  ht = 'default',
  tb = 'default',
  tr = 'default'
) {
  // luckysheet:vt(垂直), ht(水平), tb(换行), tr(旋转)
  const luckyToExcel = {
    vertical: {
      0: 'middle',
      1: 'top',
      2: 'bottom',
      default: 'top'
    },
    horizontal: {
      0: 'center',
      1: 'left',
      2: 'right',
      default: 'left'
    },
    wrapText: {
      0: false,
      1: false,
      2: true,
      default: false
    },
    textRotation: {
      0: 0,
      1: 45,
      2: -45,
      3: 'vertical',
      4: 90,
      5: -90,
      default: 0
    }
  }

  const alignment = {
    vertical: luckyToExcel.vertical[vt],
    horizontal: luckyToExcel.horizontal[ht],
    wrapText: luckyToExcel.wrapText[tb],
    textRotation: luckyToExcel.textRotation[tr]
  }
  return alignment
}

var borderConvert = function (borderType, style = 1, color = '#000') {
  // 对应luckysheet的config中borderinfo的的参数
  if (!borderType) {
    return {}
  }
  const luckyToExcel = {
    type: {
      'border-all': 'all',
      'border-top': 'top',
      'border-right': 'right',
      'border-bottom': 'bottom',
      'border-left': 'left'
    },
    style: {
      0: 'none',
      1: 'thin',
      2: 'hair',
      3: 'dotted',
      4: 'dashDot', // 'Dashed',
      5: 'dashDot',
      6: 'dashDotDot',
      7: 'double',
      8: 'medium',
      9: 'mediumDashed',
      10: 'mediumDashDot',
      11: 'mediumDashDotDot',
      12: 'slantDashDot',
      13: 'thick'
    }
  }
  const template = {
    style: luckyToExcel.style[style],
    color: { argb: color.replace('#', '') }
  }
  const border = {}
  if (luckyToExcel.type[borderType] === 'all') {
    border['top'] = template
    border['right'] = template
    border['bottom'] = template
    border['left'] = template
  } else {
    border[luckyToExcel.type[borderType]] = template
  }
  // console.log('border', border)
  return border
}

function addborderToCell (borders, rowIndex, colIndex) {
  const border = {}
  const luckyExcel = {
    type: {
      l: 'left',
      r: 'right',
      b: 'bottom',
      t: 'top'
    },
    style: {
      0: 'none',
      1: 'thin',
      2: 'hair',
      3: 'dotted',
      4: 'dashDot', // 'Dashed',
      5: 'dashDot',
      6: 'dashDotDot',
      7: 'double',
      8: 'medium',
      9: 'mediumDashed',
      10: 'mediumDashDot',
      11: 'mediumDashDotDot',
      12: 'slantDashDot',
      13: 'thick'
    }
  }
  // console.log('borders', borders)
  for (const bor in borders) {
    // console.log(bor)
    if (borders[bor].color.indexOf('rgb') === -1) {
      border[luckyExcel.type[bor]] = {
        style: luckyExcel.style[borders[bor].style],
        color: { argb: borders[bor].color.replace('#', '') }
      }
    } else {
      border[luckyExcel.type[bor]] = {
        style: luckyExcel.style[borders[bor].style],
        color: { argb: borders[bor].color }
      }
    }
  }

  return border
}

function createCellPos (n) {
  const ordA = 'A'.charCodeAt(0)

  const ordZ = 'Z'.charCodeAt(0)
  const len = ordZ - ordA + 1
  let s = ''
  while (n >= 0) {
    s = String.fromCharCode((n % len) + ordA) + s

    n = Math.floor(n / len) - 1
  }
  return s
}

<template>
  <div>
    <div>
      <input type="file" ref="file" id="wenjian" @change="getFile($event)" />
    </div>
    <button @click="downFile">下载文件</button>
    <button @click="output">导出文件</button>

    <!-- <vuedraggable v-model="msg" group="site" style="width: 300px;">
      <transition-group>
        <div class="list_item" v-for="(item, index) in msg" :key="index">
          {{ item }}
        </div>
      </transition-group>
    </vuedraggable>

    <vuedraggable v-model="blank" group="site" style="width: 300px; background-color: whitesmoke; height: 300px;" >
      <transition-group style="min-height:120px;display: block;">
        <div class="list_item" v-for="(item, index) in blank" :key="index">
          {{ item }}
        </div>
      </transition-group>
    </vuedraggable> -->

    <el-row :gutter="20" class="row">
      <div style="background-color: #999">
        <el-col :span="4"> </el-col>
      </div>

      <el-col :span="4">
        <div class="right-g" style="background-color: #999"></div>
      </el-col>

      <el-col :span="20"> </el-col>
    </el-row>
    <div id="luckysheet"></div>
  </div>
</template>

<script>
import vuedraggable from "vuedraggable";
import transitionGroup from "vuedraggable";
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
import XLSX from "xlsx/xlsx.js";
const Excel = require("exceljs");
import { exportExcel } from "@/components/export";
//console.log(XLSX.utils.aoa_to_sheet);
export default {
  props: {},
  data() {
    return {
      msg: arr,
      blank: [],
      url: "http://localhost:8080/import",
      file: "",
      options: {
        container: "luckysheet", //容器id名
        title: "", // 表 头名
        lang: "zh", // 中文
        showtoolbar: true, // 是否显示工具栏
        showinfobar: true, // 是否显示顶部信息栏
        showsheetbar: true, // 是否显示底部sheet按钮
      },
    };
  },
  methods: {
    getFile(e) {
      console.log(e.target.files[0]);
      // console.log();
      let name = e.target.files[0].name.slice(0, -5);
      console.log(name);
      let files = e.target.files[0];
      this.title = name;
      console.log(LuckyExcel);
      LuckyExcel.transformExcelToLucky(files, (exportJson, luckysheetfile) => {
        console.log(exportJson);
        console.log(luckysheetfile);
        if (exportJson.sheets == null || exportJson.sheets.length == 0) {
          alert(
            "Failed to read the content of the excel file, currently does not support xls files!"
          );
          return;
        }
        //  window.luckysheet.destroy();

        // window.luckysheet.create({
        //   container: "luckysheet", //luckysheet is the container id
        //   showinfobar: false,
        //   data: exportJson.sheets,
        //   title: exportJson.info.name,
        //   userInfo: exportJson.info.name.creator,
        // });
        console.log(this);
        this.options.data = exportJson.sheets;
        this.options.title = exportJson.info.name;
        this.options.userInfo = exportJson.info.name.creator;

        this.base();
        console.log(this.$refs.file.value);
        this.$refs.file.value = "";
        console.log(this.$refs.file.value);
      });
    },

    base() {
      window.luckysheet.create(this.options);
    },
    async output() {
      let data = window.luckysheet.getAllSheets();
      let file = await exportExcel(data, this.title);
      this.file = file;
      console.log(file);
    },

    /** 导出按钮操作 */
    async downFile() {
      console.log(this.file);
      let blob = new Blob([this.file], {
        type: "application/vnd.ms-excel;charset=utf-8",
      });
      console.log(blob);
      let downloadElement = document.createElement("a");
      let href = window.URL.createObjectURL(blob);
      downloadElement.href = href;
      document.body.appendChild(downloadElement);
      downloadElement.click();
      document.body.removeChild(downloadElement); //移除元素;防止连续点击创建多个a标签
      window.URL.revokeObjectURL(href);
    },
  },
  components: {
    vuedraggable,
   
  },
  created() {
    // console.log(55);
    //console.log(LuckyExcel);
  },
  mounted() {
    this.base();
  },
};
</script>

<style scoped lang="less">
#luckysheet {
  margin: 0px;
  padding: 0px;
  position: absolute;
  width: 90%;
  right: 0;
  top: 0px;
  bottom: 0px;
  z-index: 0;
  margin-top: 50px;
}
.row {
  height: 100%;
}
.list_item {
  background-color: pink;
  margin: 10px 0;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值