使用 “xlsx-js-style” 将数组数据导出成Excel表格

使用 “xlsx-js-style” 将数组数据导出成Excel表格

一、环境需求:
xlsx-js-style :-------------》1.2.0版本
file-saver :-------------》1.3.8版本
二、相关代码
import XLSXS from 'xlsx-js-style';
import { saveAs } from 'file-saver';

function exportExcel(data) {
    // 后端返回data是一个长度为1的json数组
    for(let i in data[0]) {
        temp.push({
          v: data[0][i],
          t: "s",
          s: { 
            font: { 
              bold: false,
              sz: 16,
              name: '宋体', 
            },
            alignment: {
              vertical: 'center', // 垂直居中
              horizontal: 'center', // 水平居中
            },
            // border 边框属性
            border: {
              top: { style: 'thin' },
              bottom: { style: 'thin' },
              left: { style: 'thin' },
              right: { style: 'thin' }
            },
          }
        })
        keys.push(i.replace(/\s+/g,'')) // 因原数据中携带空字符
    }
    const header = [
        // 第一行,需要样式,则数组中元素为对象,进行定义样式。
        [
          {
            v: this.valueAnalyCls,
            t: 's',
            s: {
              // font 字体属性
              font: {
                bold: true,
                sz: 20,
                name: '宋体',
              },
              // alignment 对齐方式
              alignment: {
                vertical: 'center', // 垂直居中
                horizontal: 'center', // 水平居中
              },
              // border 边框属性
              border: {
                top: { style: 'thin' },
                bottom: { style: 'thin' },
                left: { style: 'thin' },
                right: { style: 'thin' }
              },
              // fill 颜色填充属性
              fill: {
                fgColor: { rgb: 'D2D5DB' },
              },
            },
          },
        ],
        cellKeys,
      ]
      body.unshift(...header);
      const sheet = XLSXS.utils.aoa_to_sheet(body);
      const cols = [];
      // 每一列宽度
      keys.forEach(element => {
        cols.push({ wpx: 200 })
      });
      sheet['!cols'] = cols; // 添加到sheet中
      const rows = [
        { hpx: 32 }, 
        { hpx: 20 },
      ]
      sheet['!rows'] = rows; // 添加到sheet中
      const merge = [{ // 需要合并的单元格的位置信息
        s: { r: 0, c: 0 },
        e: { r: 0, c: keys.length - 1 }
      }];
      const workbook = XLSXS.utils.book_new();
      sheet['!merges'] = merge; // 设置合并单元格的位置信息
      XLSXS.utils.book_append_sheet(workbook, sheet, "汇总情况");
      XLSXS.writeFile(workbook, Date.now() + "汇总情况.xlsx"); // 导出 workbook
},
三、最终效果

在这里插入图片描述

四、相关参数

上述代码中,相关参数可根据实际需求更改。根据游览源码所知

列cols参数有

interface ColInfo {
	/* --- visibility --- */

	/** if true, the column is hidden */
	hidden?: boolean;

	/* --- column width --- */

	/** width in Excel's "Max Digit Width", width*256 is integral */
	width?: number;

	/** width in screen pixels */
	wpx?: number;

	/** width in "characters" */
	wch?: number;

	/** outline / group level */
	level?: number;

	/** Excel's "Max Digit Width" unit, always integral */
	MDW?: number;

	/** DBF Field Header */
	DBF?: DBFField;
}

行rows参数有

interface RowInfo {
	/* --- visibility --- */

	/** if true, the column is hidden */
	hidden?: boolean;

	/* --- row height --- */

	/** height in screen pixels */
	hpx?: number;

	/** height in points */
	hpt?: number;

	/** outline / group level */
	level?: number;
}

合并merge参数有

interface Range {
	/** Starting cell */
	s: CellAddress;
	/** Ending cell */
	e: CellAddress;
}

interface CellAddress {
	/** Column number */
	c: number;
	/** Row number */
	r: number;
}

单元格样式 (即上述代码中的s) 参数有

interface CellStyle {
	alignment?: {
		/**
		 * Horizontal alignment
		 * @default 'left'
		 */
		horizontal?: "left" | "center" | "right";
		/**
		 * Vertical alignment
		 * @default 'bottom'
		 */
		vertical?: "top" | "center" | "bottom";
		/**
		 * Rotate text
		 * - range `0` to `180`
		 * - or `255` // `255` is a special value that aligns vertically
		 * @example 180 // rotated down 180 degrees
		 */
		textRotation?: number;
		/**
		 * Wrap text
		 * @default false
		 */
		wrapText?: boolean;
	};
	border?: {
		top?: { color: CellStyleColor; style?: BorderType };
		bottom?: { color: CellStyleColor; style?: BorderType };
		left?: { color: CellStyleColor; style?: BorderType };
		right?: { color: CellStyleColor; style?: BorderType };
		diagonal?: { color: CellStyleColor; style?: BorderType; diagonalUp?: boolean; diagonalDown?: boolean };
	};
	fill?: {
		/**
		 * background color
		 */
		bgColor?: CellStyleColor;
		/**
		 * foreground color
		 */
		fgColor?: CellStyleColor;
		/**
		 * Fill pattern
		 * - `"none"` prevents fill regardless of color selection
		 * @default 'solid'
		 */
		patternType?: "solid" | "none";
	};
	font?: {
		/**
		 * bold font?
		 * @default false
		 */
		bold?: boolean;
		/**
		 * font color
		 * @example {rgb: 'FF0000'} // red color
		 */
		color?: CellStyleColor;
		/**
		 * italic font?
		 * @default false
		 */
		italic?: boolean;
		/**
		 * font face
		 * @default 'Calibri'
		 */
		name?: string;
		/**
		 * font size (points)
		 * @default 11
		 */
		sz?: number;
		/**
		 * font > effect > strikethrough
		 * @default false
		 */
		strike?: boolean;
		/**
		 * underline font?
		 * @default false
		 */
		underline?: boolean;
		/**
		 * font > effect > subscript/subscript
		 * - values: "subscript" | "superscript"
		 * @default null
		 */
		vertAlign?: "superscript" | "subscript";
	};
	/**
	 * Number format
	 * @example "0" // integer index to built in formats, see StyleBuilder.SSF property                     |
	 * @example "0.00%" // string matching a built-in format, see StyleBuilder.SSF                          |
	 * @example "0.0%" // string specifying a custom format                                                 |
	 * @example "0.00%;\\(0.00%\\);\\-;@" // string specifying a custom format, escaping special characters |
	 * @example "m/dd/yy" // string a date format using Excel's format notation                             |
	 * @default '0'
	 */
	numFmt?: string;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要修改导出Excel 表格的字体颜色,你可以使用 xlsx-style 库提供的 `XLSXStyle` 类的 `createStyle` 方法来创建自定义样式,然后将其应用到单元格中。 下面是一个使用 Vue 3 + TypeScript 和 xlsx-style-vite 库的示例代码: ```typescript <template> <div> <button @click="exportExcel">导出 Excel</button> </div> </template> <script lang="ts"> import { defineComponent } from 'vue'; import { utils, writeFile } from 'xlsx-style-vite'; import { XLSXStyle } from 'xlsx-style-vite/xlsx-style'; export default defineComponent({ methods: { exportExcel() { const data = [ ['姓名', '年龄', '性别'], ['张三', 18, '男'], ['李四', 20, '女'], ['王五', 22, '男'] ]; const workbook = utils.book_new(); const worksheet = utils.aoa_to_sheet(data); // 创建自定义样式 const style = XLSXStyle.createStyle({ font: { color: '#FF0000' } }); // 将样式应用到单元格 utils.sheet_set_cell_style(worksheet, 'A1:C1', style); utils.book_append_sheet(workbook, worksheet, 'Sheet1'); writeFile(workbook, 'example.xlsx'); } } }); </script> ``` 在上面的代码中,我们首先创建了一个包含一些数据数组 `data`。然后,我们使用 `utils.aoa_to_sheet` 方法将该数组转换为一个工作表对象。接着,我们使用 `XLSXStyle.createStyle` 方法创建了一个包含字体颜色为红色的自定义样式,并使用 `utils.sheet_set_cell_style` 方法将该样式应用到了表头行的所有单元格上。最后,我们将工作表对象添加到工作簿中,使用 `writeFile` 方法将工作簿导出为一个 Excel 文件。 需要注意的是,在使用 xlsx-style-vite 库时,要使用 `XLSXStyle` 类来创建自定义样式,这与原生的 xlsx-style 库有所不同,所以要引入 `xlsx-style-vite/xlsx-style` 模块。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值