当前位置: 首页 > 工具软件 > xls2json > 使用案例 >

xls转json

王棋
2023-12-01

```javascript
在这里插入代码片

加粗样式

var fs = require('fs')
const excelfile = "../excel-files/arz-zx-exam-view/6.xlsx";
const outDir = "../json-files/arz-zx-exam-view/"
const workbook = new Excel.Workbook()

read(0 , 1, '低端')
read(2 , 3, '高端')
async function read(areaSheetIdx, hosSheetIdx, name) {
  const areaArr =  [{
      text: '全国',
      value: '',
      seq: 10,
      children: [
        {
          "text": "全部",
          "value": "",
          "seq": 0
        }
      ]
    }]
  const cityObj = {}
  const hospital = []
  let preProvince = ''
  let preCity = ''
  let provinceCode = 10
  let cityCode = 10
  let provinceSeq = 100
  let citySeq = 100
  let hospitalSeq = 100
  await workbook.xlsx.readFile(excelfile)
  const areasheet = workbook.worksheets[areaSheetIdx]
  areasheet.eachRow(function (row, rowNumber) {
    // console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
    if (rowNumber > 1) {
      const values = row.values
      console.log(row.values)
      let province = values[2].trim()
      if (province !== preProvince) {
        preProvince = province
        provinceCode++
        cityCode = 10
        citySeq = 100
        areaArr.push({
          text: province,
          value: provinceCode,
          seq: provinceSeq,
          children: [{
            text: '全部',
            value: provinceCode,
            seq: 0
          }]
        })
        provinceSeq += 100
      }
      let city = values[3].trim()
      let cityCodex = provinceCode * 100 + cityCode
      if (city !== preCity) {
        cityCode++
        preCity = city
        areaArr[areaArr.length - 1].children.push({
          text: city,
          value: cityCodex,
          seq: citySeq
        })
        citySeq += 100
        cityObj[city] = cityCodex
      }
    }
  })
  areaArr.forEach((item, index) => {
    if (index > 0) {
      if (item.children.length == 2) {
        item.children.splice(0, 1)
      }
    }
  })
  fs.writeFile(outDir + name + '省市.json', JSON.stringify({data: areaArr}), err => {
    console.log(err)
  })
  const hossheet = workbook.worksheets[hosSheetIdx]
  hossheet.eachRow(function (row, rowNumber) {
  // console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
    if (rowNumber > 1) {
      const values = row.values
      let city = values[3].trim()
      hospital.push({
        name: values[4].trim(),
        city: cityObj[city],
        address: values[5].trim(),
        seq: hospitalSeq,
        image: values[6].split(',')
      })
      hospitalSeq+=100
    }
  })
  fs.writeFile(outDir + name + '医院.json', JSON.stringify({ data:hospital}),err => {
    console.log(err)
  })
}


 类似资料: