样式设置相关函数

样式设置包括,给表格设置边框,添加背景色,添加图片,改字号,文字局中,设置行高列宽,合并单元格等功能,开发了诸如 setExportCellStyle 辅助添加样式,setRoundBorder 用于调整边框等,makeRowConf 调整行高,makeColConf 调整列宽,makeMergeConf 处理合并。

setExportCellStyle 参数配置

辅助方法:为 sheet 级别的数据批量设置单元格属性,请一定注意第一个参数要经过 filter 函数的处理,保证 key 的顺序和完整,如果传入第四个参数(回调函数),单元格数据将会以回调函数返回的数据为准

参数名称 描述 默认值
data sheet级别的数据 undefined
range 范围字符串,比如" A1:C12"表示开始位置默认 A1,结束位置C12,目前还不支持其他格式,请不要写 A~B,1~2等自创写法 数据范围内左上角到右下角
config 批量设置的单元格属性,如果没有回调函数返回则样式合并,存在回调返回则以返回值为准 undefined
filter 回调函数,传递函数生效,返回值作为新的值(可用于过滤、规则替换样式等骚操作)『非必填参数』 undefined
filter入参列表

此参数选填,如果不传入则直接按照规则覆盖

参数名称 描述
cell 原有单元格数据
newCell 根据批量设置规则自动生成样式的单元格数据(合并)
row 所在行数据
config 传入的配置
currentCol 当前列索引
fieldKey 当前字段key
调用样例(更多用法可参考 index.js 中的样例)

如果想动态的传入范围 A1:C{数据长度},可以将第二个参数改为 'A1:C'+data.length

// 1. 假设的梳理后的后台的数据(省略filter函数梳理)
var data = [
    { username: '520',sex: '男', city: 'J', 'score': 100, 'start': '2019-03-11' },
    { username: '520',sex: '女', city: 'X', 'score': 100, 'start': '2019-03-11' },
    { username: '520',sex: '男', city: '上海', 'score': 100, 'start': '2019-03-11' }
];
// 2. 调用设置样式的函数,传入设置的范围,支持回调
excel.setExportCellStyle(data, 'A1:C3', {
    s: {
        fill: { bgColor: { indexed: 64 }, fgColor: { rgb: "FF0000" } },
        alignment: {
            horizontal: 'center',
            vertical: 'center'
        }
    }
}, function(cell, newCell, row, config, currentRow, currentCol, fieldKey) {
    // 回调参数,cell:原有数据,newCell:根据批量设置规则自动生成的样式,row:所在行数据,config:传入的配置,currentRow:当前行索引,currentCol:当前列索引,fieldKey:当前字段索引
    return ((currentRow + currentCol) % 2 === 0) ? newCell : cell;// 隔行隔列上色
} );
// 3. 导出数据
excel.exportExcel(data, '批量设置样式.xlsx', 'xlsx');

setRoundBorder 参数配置

辅助方法:设置范围内环绕的边框

【注】此方法底层与 setExportCellStyle 方法一致,所以在两个方法混合调用下可能会导致样式覆盖,特别是在使用 setExportCellStyle 的回调模式之时

参数名称 描述 默认值
data Sheet级别的数据 []
range 范围字符串,如 A1:C12,默认从左上角到右下角 "A1:C12"
config border 上下左右属性配置信息(对角线的三个属性被下放到left/right/top/bottom下) {top: {xxx}, bottom: {}, left: {}, right: {}}
调用样例
LAY_EXCEL.setRoundBorder(list, 'A1:C2', {
    top: {style: 'thick', color: {rgb: 'FFFF0000'}},
    bottom: {style: 'thick', color: {rgb: 'FFFF0000'}},
    left: {style: 'thick', color: {rgb: 'FFFF0000'}},
    right: {style: 'thick', color: {rgb: 'FFFF0000'}}
});

makeMergeConfig 参数配置

辅助方法:用于生成合并表格的配置项,注意需要传入到 exportExcel 的 opt.extend['!merge'] 中

参数名称 描述 默认值
origin 二维数组 undefined
调用样例

如下代码表示合并 A1~E1 行,并且合并 A2~D4行,如果有动态合并列的需求,请使用 JS 循环生成参数传入

var mergeConf = excel.makeMergeConfig([
    ['A1', 'E1'],
    ['A2', 'D4']
]);
excel.exportExcel({
    sheet1: data
}, '测试导出复杂表头.xlsx', 'xlsx', {
    extend: {
        // 需传入生成好的配置信息
        '!merges': mergeConf
    }
});

makeColConfig 参数配置

辅助方法:生成列宽配置,返回结果需放置于opt.extend['!cols']中

参数名称 描述 默认值
data 一个对象,对象的key代表列(如:ABCDE),value代表宽度 null
defaultNum 渲染过程中未指定单元格的默认宽度 60
使用样例

key表示列,value表示宽,配置最小列和最大列之间未定义的列宽取配置的默认值,特别注意要放在 opt.extend['!cols'] 中 这里非常感谢群里的『小星球🦏』同学,非常细致的找出了行高列宽的单位错误

// 意思是:A列40,B列80(被设置默认列宽),C列120px,D、E、F等均未定义(表格默认列宽,非 80),单位是磅
var colConf = excel.makeColConfig({
    'A': 40,
    'C': 120
}, 80);
excel.exportExcel({
    sheet1: data
}, '测试导出复杂表头.xlsx', 'xlsx', {
    extend: {
        '!cols': colConf
    }
});

makeRowConfig 参数配置

辅助方法:生成列宽配置,返回结果需放置于opt.extend['!rows']中

参数名称 描述 默认值
data 一个对象,对象的key代表从1开始的行(如:1234),value代表高度 null
defaultNum 渲染过程中未指定单元格的默认宽度 60
使用样例

key表示行,value表示高度,配置最小行和最大行之间未定义的行高取配置的默认值,特别注意要放在 opt.extend['!rows'] 中

// 意思是:1行40,2行80(被设置了默认列宽),3行120px,4/5/6/7等行均未定义(表格默认行宽,非80),1大约对应 1.1磅,由底层控制了,并未在上层封装的时候更改其单位
var rowConf = excel.makeRowConfig({
    1: 40,
    3: 120
}, 80);
excel.exportExcel({
    sheet1: data
}, '测试导出复杂表头.xlsx', 'xlsx', {
    extend: {
        '!rows': rowConf
    }
});

imageUrlToBase64 参数配置

辅助方法:下载图片并转换为 base64,返回结果需放置于 opt.extend['!images'] 中

参数名称 描述 默认值
url 图片地址,注意跨域问题 ""
ext 扩展名,默认是截取 url 的文件扩展名,支持带 ? 和 # 的 URL 识别 ""
图片锚点类型说明

插件支持两种图片锚点类型,满足不同的使用场景:

锚点类型 描述 使用场景
twoCellAnchor 图片会填充指定的单元格范围,大小随单元格变化 适合需要图片自适应单元格大小的场景
oneCellAnchor 图片使用精确尺寸,不会随单元格大小变化 适合需要精确控制图片尺寸的场景
twoCellAnchor 使用样例

注意,其中 splitPosition(pos: string) 函数一如其名,用于快速生成单元格位置配置


// 这一段是模拟生成数据,结构是: [{id: "", username: "", city: "", picture: ""}]
const data = new Array(5).fill({}).map((_, idx) => {
    return {
        id: idx,
        username: `name${idx}`,
        city: `城市${idx}`,
        picture:
        "https://img0.baidu.com/it/u=1588905690,3738625613&fm=253&fmt=auto&app=120&f=JPEG?w=801&h=500",
    };
});
// 这一段代码是异步请求图片的示例,如果本身能够拿到图片 base64,则无需这个步骤
const asyncConcurrencyTask = [];
for (let index = 0; index < data.length; index++) {
    asyncConcurrencyTask.push(
        new Promise((resolve, reject) => {
        excel
            .imageUrlToBase64(data[index].picture, "jpg")
            .then((val) => {
            pictures.push(val.split(",")[1]);
            // 注意:如果不希望表格中出现实际地址,可以在循环中驱除
            data[index].picture = ""
            resolve();
            });
        })
    );
}
await Promise.allSettled(asyncConcurrencyTask);
// 下面是导出部分 - twoCellAnchor 模式
excel.exportExcel({
    sheet1: data
}, '测试导出复杂表头.xlsx', 'xlsx', {
    extend: {
        sheet1: {
            "!images": [
            //需要为每个图片设置位置, 可根据需求动态生成图片位置(拼接字符串), 此处仅演示用法
            {
                name: "image1.jpg",
                data: pictures[0],
                opts: { base64: true },
                position: {
                type: "twoCellAnchor",
                attrs: { editAs: "oneCell" },
                from: excel.splitPosition("D2"),
                to: excel.splitPosition("E3"),
                },
            },
            {
                name: "image2.jpg",
                data: pictures[1],
                opts: { base64: true },
                position: {
                type: "twoCellAnchor",
                attrs: { editAs: "oneCell" },
                from: excel.splitPosition("D3"),
                to: excel.splitPosition("E4"),
                },
            }
            ]
        }
    }
});
oneCellAnchor 使用样例

oneCellAnchor 支持精确的尺寸控制,尺寸单位为 EMU(English Metric Units)

EMU 单位换算参考:

  • 1 英寸 = 914400 EMU
  • 1 厘米 = 360000 EMU
  • 1 像素 ≈ 9525 EMU (96 DPI)
// 数据准备部分与 twoCellAnchor 相同,此处省略...

// oneCellAnchor 模式导出
excel.exportExcel({
    sheet1: data
}, '精确尺寸图片导出.xlsx', 'xlsx', {
    extend: {
        sheet1: {
            "!images": [
            {
                name: "precise_image1.jpg",
                data: pictures[0],
                opts: { base64: true },
                position: {
                type: "oneCellAnchor",
                from: excel.splitPosition("D2"),  // 起始位置
                ext: {
                    cx: 914400,  // 宽度:1英寸 = 914400 EMU
                    cy: 685800   // 高度:0.75英寸 = 685800 EMU
                }
                },
            },
            {
                name: "precise_image2.jpg",
                data: pictures[1],
                opts: { base64: true },
                position: {
                type: "oneCellAnchor",
                from: excel.splitPosition("D4"),
                ext: {
                    cx: 1828800, // 宽度:2英寸
                    cy: 914400   // 高度:1英寸
                }
                },
            },
            {
                name: "precise_image3.jpg",
                data: pictures[2],
                opts: { base64: true },
                position: {
                type: "oneCellAnchor",
                from: {
                    c: 3,      // D列 (从0开始)
                    r: 5,      // 第6行 (从0开始)
                    colOff: 0, // 列偏移(EMU单位)
                    rowOff: 0  // 行偏移(EMU单位)
                },
                ext: {
                    cx: 1440000, // 宽度:约1.57英寸
                    cy: 1080000  // 高度:约1.18英寸
                }
                },
            }
            ]
        }
    }
});
position 配置详解

通用属性: | 属性名 | 描述 | 类型 | 必填 | | ------ | ---- | ---- | ---- | | type | 锚点类型 | "twoCellAnchor" | "oneCellAnchor" | ✓ | | from | 起始位置 | object | ✓ |

twoCellAnchor 特有属性: | 属性名 | 描述 | 类型 | 必填 | | ------ | ---- | ---- | ---- | | to | 结束位置 | object | ✓ | | attrs.editAs | 编辑行为 | "oneCell" | "twoCell" | "absolute" | × |

oneCellAnchor 特有属性: | 属性名 | 描述 | 类型 | 必填 | | ------ | ---- | ---- | ---- | | ext.cx | 图片宽度(EMU单位) | number | ✓ | | ext.cy | 图片高度(EMU单位) | number | ✓ |

from/to 位置对象: | 属性名 | 描述 | 类型 | 默认值 | | ------ | ---- | ---- | ------ | | c | 列索引(从0开始) | number | 0 | | r | 行索引(从0开始) | number | 0 | | colOff | 列偏移(EMU单位,仅 oneCellAnchor) | number | 0 | | rowOff | 行偏移(EMU单位,仅 oneCellAnchor) | number | 0 |

混合使用示例
excel.exportExcel({
    sheet1: data
}, '混合模式图片导出.xlsx', 'xlsx', {
    extend: {
        sheet1: {
            "!images": [
            // 使用 twoCellAnchor 填充单元格区域
            {
                name: "auto_size.jpg",
                data: pictures[0],
                opts: { base64: true },
                position: {
                type: "twoCellAnchor",
                from: excel.splitPosition("B2"),
                to: excel.splitPosition("C4"),
                },
            },
            // 使用 oneCellAnchor 精确控制尺寸
            {
                name: "exact_size.jpg", 
                data: pictures[1],
                opts: { base64: true },
                position: {
                type: "oneCellAnchor",
                from: excel.splitPosition("E2"),
                ext: {
                    cx: 914400,  // 1英寸宽
                    cy: 914400   // 1英寸高,正方形
                }
                },
            }
            ]
        }
    }
});

convertEMU 参数配置

辅助方法:EMU 单位转换函数,简化图片尺寸计算

参数名称 描述 类型 默认值
value 输入数值 number 必填
fromUnit 输入单位:'inch'/'in'(英寸), 'cm'(厘米), 'px'/'pixel'(像素), 'emu' string 必填
toUnit 输出单位:'inch'/'in'(英寸), 'cm'(厘米), 'px'/'pixel'(像素), 'emu' string 'emu'
调用样例
// 英寸转 EMU
const width_emu = excel.convertEMU(2, 'inch');        // 1828800
const height_emu = excel.convertEMU(1.5, 'in');       // 1371600

// 厘米转 EMU  
const width_cm = excel.convertEMU(5, 'cm');           // 1800000
const height_cm = excel.convertEMU(2.5, 'cm');        // 900000

// 像素转 EMU(基于 96 DPI)
const width_px = excel.convertEMU(200, 'px');         // 1905000
const height_px = excel.convertEMU(100, 'pixel');     // 952500

// EMU 转其他单位
const inches = excel.convertEMU(914400, 'emu', 'inch'); // 1
const cm = excel.convertEMU(360000, 'emu', 'cm');       // 1
const pixels = excel.convertEMU(9525, 'emu', 'px');     // 1

createOneCellAnchor 参数配置

辅助方法:快速创建 oneCellAnchor 类型的图片位置配置

参数名称 描述 类型 默认值
position 图片位置,支持字符串(如 "D2")或对象(如 {c: 3, r: 1}) string \ object 必填
width 图片宽度 number 必填
height 图片高度 number 必填
unit 尺寸单位 string 'emu'
options 可选配置 {colOff, rowOff} object {}
调用样例
// 使用字符串位置,像素单位
const position1 = excel.createOneCellAnchor("D2", 200, 150, "px");

// 使用对象位置,英寸单位
const position2 = excel.createOneCellAnchor(
  {c: 3, r: 1}, 
  2, 1.5, "inch"
);

// 带偏移量的配置,厘米单位
const position3 = excel.createOneCellAnchor(
  "F4", 
  5, 3, "cm",
  {
    colOff: excel.convertEMU(0.5, 'cm'),  // 向右偏移 0.5cm
    rowOff: excel.convertEMU(0.25, 'cm')  // 向下偏移 0.25cm
  }
);

// 使用辅助函数简化图片配置
const imageConfig = [
  {
    name: "image1.jpg",
    data: pictures[0],
    opts: { base64: true },
    position: excel.createOneCellAnchor("D2", 100, 100, "px")
  },
  {
    name: "image2.jpg", 
    data: pictures[1],
    opts: { base64: true },
    position: excel.createOneCellAnchor("D4", 2, 1.5, "inch")
  }
];

excel.exportExcel({
    sheet1: data
}, '使用辅助函数的图片导出.xlsx', 'xlsx', {
    extend: {
        sheet1: {
            "!images": imageConfig
        }
    }
});

results matching ""

    No results matching ""