search
HomeWeb Front-endJS TutorialThe solution to the problem of js exporting Excel table exceeding 26 English characters ES6

The following editor will bring you an ES6 solution to the problem of js exporting Excel tables exceeding 26 English characters. It has a good reference and value for learning js. If you are interested in js, please follow the editor to have a look. I hope it will be helpful to everyone.

This requires some understanding of the header encoding rules of Excel tables. Currently, the sample code only extends to 52 fields


/**
*json数据导入导出Excel表格示例代码
*
/
 
var array_utils = require('./utils-array')
var XLSX = require("xlsx");

module.exports = {
 writeExcel : function (headers,data,file,callback) {
  if(data.length ==0){
   var obj = {}
   for(var v of headers){
    obj[v] = ''
   }
   data.push(obj)
  }
  _writeExcel(headers,data,file,callback)
 },

 /**
  * 获取excel原始信息
  * @param path 文件路径
  */
 info : function(path){
  return _info(path)
 },
 /**
  * 格式化excel原始信息
  * @param path 文件路径
  */
 formate_info : function (path) {
  return info_formate_info(path).formate
 },
 info_formate_info : function (path) {
  return info_formate_info(path)
 }

}

var _info = function(path) {
 var k = XLSX.readFile(path, {type: 'base64'});
 var result = {}
 k.SheetNames.forEach(function(sheetName) {
  var worksheet = k.Sheets[sheetName];
  result[sheetName] = XLSX.utils.sheet_to_json(worksheet);
 });
 return result
}

var info_formate_info = function(path){
 var info = _info(path)
 var result = {}
 for(var value in info){
  result[value] = {}
 }
 for(var key_info in info ){
  var array = info[key_info]
  if(array_utils.isArray(array) || array.length>0){
   var keys_array = Object.keys(array[0])
   var obj = {}
   for(var value of keys_array){
    obj[value] = []
   }
   for( var key in obj ){
    var subject_clone = JSON.parse(JSON.stringify(array))
    subject_clone.filter( (v)=>{
     for(var k in v){
      if(k!=key){
       delete v[k]
      }
     }
     return v;
    })
    var subject_key_value = Array.from(array_utils.arrayQC(subject_clone),v => v[key] )
    var obA = []
    for(var v of subject_key_value){
     var obk = {
      id : null,
      v : v
     }
     for(var ke in keys_array){
      var thisIndex = keys_array.findIndex(x=>x==keys_array[ke])
      var currentIndex = keys_array.findIndex(x=>x==key)
      if( thisIndex < currentIndex){
       try {
        var thisObj = array.find(x=>x[ key ] == v )
        obk[keys_array[ke]] = thisObj[ keys_array[ke] ]
       }catch (e){
        console.error(e)
       }
      }
     }

     obA.push(obk)
    }
    obj[key] = obA
   }
   result[key_info]= obj
  }
 }
 return {
  info : info,
  formate : result
 }
}

var _writeExcel = function (headers,data,file,callback) {
 var _headers = headers
 var _data = data;
 var headers = _headers
 // 为 _headers 添加对应的单元格位置
  .map((v, i) => Object.assign({}, {
   v: v,
   position:num(i)+1
  }))
  // 转换成 worksheet 需要的结构
  .reduce((prev, next) => Object.assign({}, prev, {[next.position]: {v: next.v}}), {});
 var data = _data
  .map((v, i) => _headers.map((k, j) => Object.assign({}, {
   v: v[k],
   position:num(j) + (i+2)
  })))
  // 对刚才的结果进行降维处理(二维数组变成一维数组)
  .reduce((prev, next) => prev.concat(next))
  // 转换成 worksheet 需要的结构
  .reduce((prev, next) => Object.assign({}, prev, {[next.position]: {v: next.v}}), {});
// 合并 headers 和 data
 // console.log("测试data",data)
 var output = Object.assign({}, headers, data);
// 获取所有单元格的位置
 var outputPos = Object.keys(output);
// 计算出范围
 var ref = outputPos[0] + &#39;:&#39; + outputPos[outputPos.length - 1];
// 构建 workbook 对象
 var wb = {
  SheetNames: [&#39;Sheet1&#39;],
  Sheets: {
   &#39;Sheet1&#39;: Object.assign({}, output, { &#39;!ref&#39;: ref })
  }
 };

 // 导出 Excel
 XLSX.writeFileAsync( file , wb,function (err) {
  callback(err)
 });
}
//定位Excel位置
var num=function(i){
 var n=parseInt(i+65)
 if(n>90){
  n=String.fromCharCode(65)+String.fromCharCode(i+39)
  return n
 }else {
  n=String.fromCharCode(n)
  return n
 }

}


The above ES6 solution to the problem of js exporting Excel table exceeding 26 English characters is what the editor shared with you. That’s all, I hope it can be a reference for everyone!

Related recommendations:

js export formatted excel instance method

ie browser uses js to export web pages to excel and print

js export table to excel and is compatible with FF and IE examples

The above is the detailed content of The solution to the problem of js exporting Excel table exceeding 26 English characters ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools