美文网首页
js读取xls或xlsx

js读取xls或xlsx

作者: 明翼 | 来源:发表于2020-12-12 11:00 被阅读0次
import XLSX from 'xlsx'
function readXLS (data, xlsxSheetName, headline = 0) {
  try {
    const workbook = XLSX.read(data, { type: 'binary', sheetRows: headline });
    console.log("After read file")
    var sheetNames = workbook.SheetNames;
    var extractSheet = sheetNames[0]
    if (xlsxSheetName !== null) {
      extractSheet = xlsxSheetName
    }
    const csv = XLSX.utils.sheet_to_csv(worksheet)
    const datas = csv.split("\n")
    const fieldNames = datas[headline - 1]
    const filedLists = fieldNames.split(",")
    return filedLists
  } catch (e) {
    this.$message.error("读取execle文件异常:" + e)
    return null
  }
}

## 读取xls 一样的,只是sheet名字为Sheet1不是和上面类似了,936解决gbk乱码问题
function readXLS2 (data, headline = 0) {
  try {
    const workbook = XLSX.read(data, { type: 'binary', sheetRows: headline, codepage: 936 });
    var sheetNames = workbook.SheetNames;
    var extractSheet = sheetNames[0]
    var worksheet = workbook.Sheets[extractSheet];
    const csv = XLSX.utils.sheet_to_csv(worksheet)
    const datas = csv.split("\n")
    const fieldNames = datas[headline - 1]
    console.log("extract field names:" + fieldNames)
    const filedLists = fieldNames.split(",")
    return filedLists
  } catch (e) {
    this.$message.error("读取execle文件异常:" + e)
    return null
  }
}

# cvs乱码
reader.readAsText(file, 'gbk');

相关文章

网友评论

      本文标题:js读取xls或xlsx

      本文链接:https://www.haomeiwen.com/subject/fiuegktx.html