npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@sparta-utils/excel-validate-helper

v1.4.4

Published

Excel 读取、校验、错误标注和导出工具库

Downloads

257

Readme

📊 excel-validate-helper

npm version license downloads

一个功能强大、灵活易用的 Excel 数据处理工具库,提供读取、校验、错误标注和导出一站式解决方案 �?

[快速开始](#快速开 �? �?[功能特性](#功能特 �? �?详细文档 �?完整示例


�?功能特 �?

  • 🚀 Excel 读取:支 �?.xlsx 文件读取,自动识别日期格式,灵活配置数据起始 �?
  • �?数据校验:支持必填、类型、范围、正则、唯一性等多种校验规则
  • 🎨 错误标注:在 �?Excel 文件中标注错误单元格,支持批注和错误列输 �?
  • 📥 文件导出:支持多种格式文件导出,兼容主流浏览 �?
  • 🔧 *高度可配 �?:每个模块都提供丰富的配置选项
  • 💪 TypeScript 支持:完整的类型定义,开发体验更 �?

📦 安装

# 使用 npm
npm install @sparta-utils/excel-validate-helper

# 使用 yarn
yarn add @sparta-utils/excel-validate-helper

# 使用 pnpm
pnpm add @sparta-utils/excel-validate-helper

🚀 快速开 �?

基本导入

import {
  ExcelReader,
  ExcelValidator,
  ExcelMarker,
  ExcelExporter,
} from '@sparta-utils/excel-validate-helper'

完整流程示例

async function handleExcelFile(file: File) {
  try {
    // 1。�?读取 Excel 文件
    const { headers, data } = await ExcelReader.read(file, {
      dataStartRow: 4,           // 数据从第 4 行开始,�?3 行是表头
      autoDetectDate: true,      // 自动识别并转换日期格�?
      filterEmptyRows: true,     // 过滤空行
      onProgress: (progress) => {
        console.log(`读取进度�?{progress}%`)
      }
    })

    console.log('表头:', headers)
    console.log('数据:', data)

    // 2。✅ 校验数据
    const validationResult = ExcelValidator.validate(data, {
      colHeaders: ['姓名', '身份�?, '手机�?, '年龄', '邮箱'],
      fieldNames: ['name', 'idCard', 'phone', 'age', 'email'],
      rules: {
        0: { required: true },
        1: {
          required: true,
          pattern: ExcelValidator.getPredefinedPattern('idCard')
        },
        2: { pattern: ExcelValidator.getPredefinedPattern('phone') },
        3: { type: 'number', min: 18, max: 65 },
        4: { pattern: ExcelValidator.getPredefinedPattern('email') }
      },
      uniqueGroupCols: [1, 2],  // 身份�?+ 手机号联合唯一
      onProgress: (current, total) => {
        console.log(`校验进度: ${current}/${total}`)
      }
    })

    if (validationResult.err.length > 0) {
      // 3。�?有错误,标注错误单元�?
      console.warn('校验失败,错误数�?', validationResult.err.length)

      const markedBlob = await ExcelMarker.markErrors(file, validationResult.err, {
        outputType: 'both',              // 同时使用批注和错误列
        allowMultiSheet: true,           // 允许�?Sheet 标注
        errorColumnTitle: '数据校验信息',
        errorColumnIndex: 10             // 错误信息显示在第 10 �?
      })

      // 4。�?导出带有错误标注�?Excel
      ExcelExporter.export(markedBlob, {
        fileName: '错误标注结果.xlsx',
        format: 'xlsx',
        onSuccess: () => console.log('�?文件导出成功'),
        onError: (err) => console.error('�?导出失败', err)
      })
    } else {
      // 校验通过,处理成功数�?
      console.log('�?校验通过,数�?', validationResult.succ)
      // 继续业务逻辑...
    }
  } catch (error) {
    console.error('处理失败:', error)
  }
}

📋 目录


📦 核心模块

1。ExcelReader - Excel 读取

📖 查看完整文档

支持读取 .xlsx 文件,自动识别日期格式,灵活配置数据起始行、工作表索引、进度回调等 �?

*主要功能 �?

  • �?自动识别并转 �?Excel 日期格式(新特性)
  • �?支持自定义表头和数据映射
  • �?自动过滤空行
  • �?进度回调支持

快速使用:

const result = await ExcelReader.read(file, {
  dataStartRow: 4, // 数据开始行(默�?4�?
  autoDetectDate: true, // 自动识别日期(默�?true�?
  dateFormat: 'YYYY-MM-DD HH:mm:ss', // 日期格式
  filterEmptyRows: true, // 过滤空行
  onProgress: (progress) => console.log(`${progress}%`),
})

console.log(result.headers) // 表头数组
console.log(result.data) // 数据二维数组

*返回结果 �?

interface ExcelReadResult {
  headers: string[] // 表头数组
  data: any[][] // 数据二维数组(首列是 Excel 行号�?
  totalRows: number // 总行�?
  sheetName: string // 工作表名�?
  fileName: string // 文件�?
}

2。ExcelValidator - 数据校验

📖 查看完整文档

功能强大的数据校验工具,支持必填、类型、范围、正则、唯一性等多种校验规则 �?

*主要功能 �?

  • �?必填项、数字范围校 �?
  • �?内置正则:邮箱、手机号、身份证 �?
  • �?单列唯一 / 组合列唯一校验
  • �?自定义正则和函数校验
  • �?自动类型转换(数字、布尔等 �?

快速使用:

const result = ExcelValidator.validate(data, {
  colHeaders: ['姓名', '身份�?, '手机�?, '年龄', '邮箱'],
  fieldNames: ['name', 'idCard', 'phone', 'age', 'email'],
  rules: {
    0: { required: true },
    1: {
      required: true,
      pattern: ExcelValidator.getPredefinedPattern('idCard')
    },
    2: { pattern: ExcelValidator.getPredefinedPattern('phone') },
    3: { type: 'number', min: 18, max: 65 },
    4: { pattern: ExcelValidator.getPredefinedPattern('email') }
  },
  uniqueGroupCols: [1, 2],  // 身份�?+ 手机号联合唯一
})

console.log(result.err)   // 错误列表
console.log(result.succ)  // 成功数据对象数组

*内置正则模板 �?

ExcelValidator.getPredefinedPattern('idCard') // 身份�?
ExcelValidator.getPredefinedPattern('phone') // 手机�?
ExcelValidator.getPredefinedPattern('tel') // 固话
ExcelValidator.getPredefinedPattern('email') // 邮箱

3。ExcelMarker - 错误标注

📖 查看完整文档

�?Excel 文件中标注错误单元格,支持批注、样式修改和错误列输出 �?

*主要功能 �?

  • �?支持单元格批注和样式修改
  • �?支持错误等级:error / warning / info
  • �?支持在额外列中记录错误信 �?
  • �?支持 �?Sheet 标注
  • �?灵活的输出方式:note / column / both

快速使用:

const errors = [
  { row: 2, col: 3, reason: '缺失必填�?, level: 'error' },
  { row: 3, col: 2, reason: '数值超�?, level: 'warning' },
  { row: 4, col: 5, reason: '格式建议', level: 'info' }
]

const markedBlob = await ExcelMarker.markErrors(file, errors, {
  outputType: 'both',              // 'note' | 'column' | 'both'
  allowMultiSheet: true,           // 允许�?Sheet 标注
  errorColumnTitle: '数据校验信息',
  errorColumnIndex: 10             // 错误列插入位�?
})

*错误等级样式 �?

| Level | 背景 �? | 字体 �? | 描述 | | --------- | ---------- | --------- | -------- | | error | 🔴 红色 | #FF0000 | 严重错误 | | warning | 🟡 黄色 | #996600 | 警告提示 | | info | 🟢 蓝绿 �? | #0000FF | 信息提示 |


4。ExcelExporter - 文件导出

📖 查看完整文档

通用的浏览器端文件导出工具,支持多种格式和浏览器兼容 �?

*主要功能 �?

  • �?支持多种文件格式:xlsx / csv / pdf
  • �?兼容现代浏览器与 IE
  • �?支持导出回调:成功、失败、进 �?
  • �?自动补全文件扩展 �?

快速使用:

ExcelExporter.export(blob, {
  fileName: '导出文件.xlsx',
  format: 'xlsx', // 'xlsx' | 'csv' | 'pdf'
  onSuccess: () => console.log('�?导出成功'),
  onError: (err) => console.error('�?导出失败', err),
  onProgress: (progress) => console.log(`${progress}%`),
})

📖 详细文档

每个模块都有独立的详细文档,包含完整 �?API 说明、参数配置和使用示例 �?

| 模块 | 说明 | 文档链接 | | ------------------ | --------------------- | ----------------------------------- | | ExcelReader | Excel 文件读取与解 �? | 📖 查看文档 | | ExcelValidator | 数据校验与验 �? | 📖 查看文档 | | ExcelMarker | 错误单元格标 �? | 📖 查看文档 |


�?常见问题

1. 如何处理大文件?

对于大型 Excel 文件,建议:

  • 使用 onProgress 回调显示进度
  • 设置 maxRows 限制读取行数
  • 设置 emptyRowThreshold 避免读取过多空行
const result = await ExcelReader.read(file, {
  maxRows: 10000, // 最多读�?10000 �?
  emptyRowThreshold: 50, // 连续 50 个空行后停止
  onProgress: (progress) => {
    updateProgressBar(progress) // 更新进度�?
  },
})

2. 日期格式识别不准确怎么办?

ExcelReader 会自动识 �?Excel 中的日期格式单元格。如果识别不准:

// 方法 1:关闭自动识别,使用 mapRow 自己处理
const result = await ExcelReader.read(file, {
  autoDetectDate: false,
  mapRow: (row) => {
    // 自己处理日期�?
    row[5] = formatDate(row[5])
    return row
  }
})

// 方法 2:自定义日期格式
const result = await ExcelReader.read(file, {
  autoDetectDate: true,
  dateFormat: 'YYYY年MM月DD�?  // 自定义格�?
})

3. 如何处理多个工作表?

使用 sheetIndex 参数指定要读取的工作表:

// 读取第一个工作表
const sheet1 = await ExcelReader.read(file, { sheetIndex: 0 })

// 读取第二个工作表
const sheet2 = await ExcelReader.read(file, { sheetIndex: 1 })

// 批量读取所有工作表
for (let i = 0; i < 3; i++) {
  const sheet = await ExcelReader.read(file, { sheetIndex: i })
  console.log(`工作�?${sheet.sheetName}:`, sheet.data)
}

4. 校验错误信息中的行号对应关系 �?

  • ExcelReader.read() 返回 �?data 数组,每行的**第一个元 �?*�?Excel 的实际行 �?
  • ExcelValidator.validate() 返回的错误信息中,row 字段也是 Excel 的实际行 �?
  • col 字段 �?0 开始计 �?
const { data } = await ExcelReader.read(file, { dataStartRow: 4 })
console.log(data[0][0])  // 输出: 4(Excel 的第 4 行)

const result = ExcelValidator.validate(data, { ... })
console.log(result.err[0])
// 输出: { row: 4, col: 2, reason: '...' }
// row: 4 表示 Excel 的第 4 �?
// col: 2 表示�?3 列(�?0 开始)

5. 如何自定义错误标注样式?

使用 style 参数自定义样式:

const markedBlob = await ExcelMarker.markErrors(file, errors, {
  outputType: 'both',
  style: {
    font: {
      color: { argb: 'FFFF0000' }, // 红色字体
      bold: true,
    },
    fill: {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFFFFF00' }, // 黄色背景
    },
    border: {
      top: { style: 'thin', color: { argb: 'FF000000' } },
      left: { style: 'thin', color: { argb: 'FF000000' } },
      bottom: { style: 'thin', color: { argb: 'FF000000' } },
      right: { style: 'thin', color: { argb: 'FF000000' } },
    },
  },
})

6. 支持哪些浏览器?

  • 现代浏览器:Chrome、Firefox、Safari、Edge(基 �?Chromium�?
  • 旧版浏览器:IE 10+(使 �?msSaveOrOpenBlob�?

7. 如何 �?Node.js 中使用?

本库主要为浏览器环境设计。如果需要在 Node.js 中使用,需要:

npm install xmldom --save-dev
const { DOMParser } = require('xmldom')
if (typeof global !== 'undefined' && !global.DOMParser) {
  global.DOMParser = DOMParser
}

📝 更新日志

v1.4.3 (2025-01-12)

  • �?新增:ExcelReader 支持自动识别并转 �?Excel 日期格式
  • 🐛 修复:日期转换的时区问题,使 �?UTC 时间
  • 🐛 修复:普通数字被错误识别为日期的问题
  • �?增强:ExcelValidator 支持字符串长度校 �?
  • �?增强:ExcelValidator 支持布尔值自动转 �?

v1.4.0

  • �?新增:ExcelMarker 支持 �?Sheet 标注
  • �?新增:ExcelReader 支持 maxRows �?emptyRowThreshold 参数
  • 🐛 修复:大文件读取内存问题

v1.3.0

  • �?新增:ExcelValidator 支持组合列唯一校验
  • �?新增:内置常用正则模板(身份证、手机号、邮箱)
  • �?优化:数字类型自 �?trim 和转 �?

🤝 贡献指南

欢迎贡献代码、报 �?Bug 或提出新功能建议 �?

  1. Fork 本仓 �?
  2. 创建你的特性分 �?(git checkout -b feature/AmazingFeature)
  3. 提交你的修改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 发起 Pull Request

📝 许可 �?

MIT License - 详见 LICENSE 文件


📧 联系方式

  • 作者:lihongquan
  • 邮箱:[email protected]
  • 如有疑问或功能需求,欢迎反馈 �?

如果这个工具对你有帮助,请给 �?Star ⭐️ 支持一下!

Made with ❤️ by lihongquan