Vue imports and exports excel, sets cell background color, centers text, merges cells, sets column width (using xlsx library and xlsx-style library)

xlsx

xlsxIt is SheetJSan npm library for processing excel files developed by

It is suitable for front-end developers to realize the classic requirements of importing and exporting excel files

In order to distinguish it from xlsx files and highlight its application language, this library is usually calledjs-xlsx

Export js data as an Excel file

The following steps are required:

  1. Install the xlsx library You can use the npm package manager to install the xlsx library, or you can download the xlsx to the local, and then import it through the script tag in the HTML file.
  2. Prepare data Prepare the data to be exported and store it as an array or object.
  3. Create a workbook Create a workbook (workbook) object through utils.book_new()the method , which contains one or more worksheets (worksheet).
  4. Create a worksheet Create a worksheet through utils.json_to_sheet()the method , and pass the prepared data into this method as a parameter. If multiple worksheets need to be created, this method can be called multiple times and they will be added to the workbook object.
  5. Add a worksheet to a workbook Add the created worksheet to the workbook object through utils.book_append_sheet()the method .
  6. Export data Export the workbook object to an Excel file through writeFile()the method . You can specify the exported file name and file format, such as .xlsxor .csv.

The following is a sample code to export data to an Excel file using the xlsx library:

vue

<script setup>
import * as XLSX from "xlsx/xlsx.mjs";
const download = () => {
    
    
  const data = [
    ["姓名", "年龄", "性别"],
    ["张三", 18, "男"],
    ["李四", 22, "女"],
    ["王五", 25, "男"],
  ];
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.json_to_sheet(data);
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
  XLSX.writeFile(workbook, "data.xlsx");
};
</script>

<template>
  <button @click="download">导出</button>
</template>

Import Excel file to generate js data

  1. Use input type="file" to select xlsx file
  2. Use fileReader to read files as binary encoding
  3. The XLSX.read method handles binary encoding as a worksheet object
  4. XLSX.utils.sheet_to_json converts the worksheet object to json data, which is actually a js array
  5. Finally, the array data can be processed into the format you want
<template>
  <article>
    <p>导入高德地图xlsx文件</p>
    <input type="file" ref="upload" accept=".xls,.xlsx" />
  </article>
</template>

<script>
import XLSX from "xlsx"
export default {
    
    
  mounted() {
    
    
    // 监听表格导入事件
    this.$refs.upload.addEventListener("change", e => {
    
    
      this.readExcel(e)
    })
  },
  methods: {
    
    
    readExcel(e) {
    
    
      //表格导入
      const files = e.target.files
      //如果没有文件名,不往下执行
      if (files.length <= 0) return
      // 上传文件格式不正确,非xls或者xlsx格式文件,不往下执行
      if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) return
      const fileReader = new FileReader()
      // readAsBinaryString将文件读取为二进制编码
      fileReader.readAsBinaryString(files[0])
      // 读取完成
      fileReader.onload = ev => {
    
    
        try {
    
    
          // 二进制数据
          const data = ev.target.result
          // xlsx处理二进制数据
          const workbook = XLSX.read(data, {
    
    
            type: "binary"
          })
          //取第一张表
          const wsname = workbook.SheetNames[0] 
          // 根据表格内容生成json数据
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) 
          const outputs = [] //清空接收数据
          for (let i = 0; i < ws.length; i++) {
    
    
            const sheetData = {
    
    
              value: ws[i].adcode,
              label: ws[i].中文名
            }
            outputs.push(sheetData)
          }
        } catch (e) {
    
    
          console.log(e)
        }
      }
    }
  }
}
</script>

The xlsx-js-style library uses

The xlsx base library does not provide style settings, you can use the xlsx-js-style library, which is a fork version of the xlsx library, and adds style definitions

Detailed styles can be viewed at https://github.com/gitbrent/xlsx-js-style/

Can adjust background color, font style, border

npm i -s xlsx-js-style
<script setup>
import XLSX from "xlsx-js-style";
console.log();
const download = () => {
    
    
  const wb = XLSX.utils.book_new();
  const ws = XLSX.utils.aoa_to_sheet([
    ["Hello", "World"],
    [1, 2],
  ]);
  // 在单元格对象中添加 `s` 属性来设置该单元格的样式
  ws["A1"].s = {
    
    
    font: {
    
     bold: true },
    alignment: {
    
     horizontal: "center" },
    fill: {
    
     fgColor: {
    
     rgb: "FFFF0000" } },
  };
  ws["B2"].s = {
    
    
    alignment: {
    
     horizontal: "center" },
    font: {
    
     bold: true },
    fill: {
    
     fgColor: {
    
     rgb: "FFFF0000" } },
  };
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
  XLSX.writeFile(wb, "example.xlsx");
};
</script>

remove header

XLSX.utils.json_to_sheetObject.keysBy default the header is generated using

So if the following data format is not added , the index header skipHeader: truewill appear0 1 2

<script setup>
import XLSX from "xlsx-js-style";
const download = () => {
    
    
  const data = [
    ["姓名", "年龄", "性别"],
    ["张三", 18, "男"],
    ["李四", 22, "女"],
    ["王五", 25, "男"],
  ];
  const wb = XLSX.utils.book_new();
  const ws = XLSX.utils.json_to_sheet(data, {
    
    
    skipHeader: true,
  });
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
  XLSX.writeFile(wb, "example.xlsx");
};
</script>

<template>
  <button @click="download">导出</button>
</template>

set column width

<script setup>
import XLSX from "xlsx-js-style";
const download = () => {
    
    
  const data = [
    {
    
     姓名: "张三", 年龄: 18, 性别: "男" },
    {
    
     姓名: "李四", 年龄: 20, 性别: "女" },
    {
    
     姓名: "王五", 年龄: 22, 性别: "男" },
  ];
  const wb = XLSX.utils.book_new();
  const ws = XLSX.utils.json_to_sheet(data);
  ws["!cols"] = [
    {
    
    
      wpx: 150,
    },
    {
    
    
      wpx: 500,
    },
    {
    
    
      wpx: 100,
    },
  ];
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
  XLSX.writeFile(wb, "example.xlsx");
};
</script>

<template>
  <button @click="download">导出</button>
</template>

Merge Cells

<script setup>
import XLSX from "xlsx-js-style";
const download = () => {
    
    
  const data = [
    {
    
     姓名: "张三", 年龄: 18, 性别: "男" },
    {
    
     姓名: "李四", 年龄: 20, 性别: "女" },
    {
    
     姓名: "王五", 年龄: 22, 性别: "男" },
  ];
  const wb = XLSX.utils.book_new();
  const ws = XLSX.utils.json_to_sheet(data);
  // s 表示要合并的单元格范围的左上角单元格,r 表示该单元格的行号,c 表示该单元格的列号,行列号从 0 开始计数。所以 { r: 0, c: 0 } 表示第 1 行第 1 列的单元格,即 A1 单元格。
  // e 表示要合并的单元格范围的右下角单元格,其含义与 s 相同。所以 { r: 0, c: 1 } 表示第 1 行第 2 列的单元格,即 B1 单元格。
  // 因此,{ s: { r: 0, c: 0 }, e: { r: 0, c: 1 } } 表示要合并第 1 行第 1 列和第 1 行第 3 列之间的元格。
  // 注意,合并会以开始位置单元格中的内容为准,所以合并后的单元格中的内容为 A1 单元格中的内容。
  ws["!merges"] = [{
    
     s: {
    
     r: 0, c: 0 }, e: {
    
     r: 0, c: 2 } }];
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
  XLSX.writeFile(wb, "example.xlsx");
};
</script>

<template>
  <button @click="download">导出</button>
</template>

Guess you like

Origin blog.csdn.net/qq_42611074/article/details/130580395
Recommended