Javascript 正在尝试从excel到JS获取信息

Javascript 正在尝试从excel到JS获取信息,javascript,excel,Javascript,Excel,我做了一个货币转换器,我把所有的货币汇率放在一个.xlsx(excel文件)中,数据会自动更新和保存,所以我不能将其保存为.csv并将数据解析到脚本中。我需要知道如何直接从excel到JavaScript获取数据(我只懂JavaScript,所以如果您使用另一种语言,如果您能发送完整的代码,我会很高兴) 这是网站本身: 标题 { 位置:固定; 宽度:100%; 排名:0; 背景图片:url(../images/banner-1103703_960_720.jpg); 盒影:0 0 4px灰色;

我做了一个货币转换器,我把所有的货币汇率放在一个.xlsx(excel文件)中,数据会自动更新和保存,所以我不能将其保存为.csv并将数据解析到脚本中。我需要知道如何直接从excel到JavaScript获取数据(我只懂JavaScript,所以如果您使用另一种语言,如果您能发送完整的代码,我会很高兴)

这是网站本身:

标题
{
位置:固定;
宽度:100%;
排名:0;
背景图片:url(../images/banner-1103703_960_720.jpg);
盒影:0 0 4px灰色;
}
身体
{
边际:0px;
背景色:#6eaac4;
}
#转换器
{
填充顶部:230px;
文本对齐:居中;
}
#标志
{
最大宽度:340px;
}
#到
{
字体大小:40px;
颜色:耐火砖;
字体家族:幻想;
}
选择
{
宽度:300px;
高度:50px;
线高:50px;
边界半径:15px;
背景颜色:浅蓝色;
字体大小:20px;
}
文章
{
背景色:黄绿色;
边界半径:50px;
边框颜色:黑色;
宽度:340px;
高度:自动;
}
按钮
{
/*绿色的*/
背景色:白烟;
背景重复:无重复;
边界:4px;
光标:指针;
溢出:隐藏;
边界半径:30px;
大纲:无;
颜色:耐火砖;
文本对齐:居中;
字体家族:幻想;
字母间距:5px;
文字装饰:无;
字体大小:50px;
}
输入
{
背景颜色:浅蓝色;
边界半径:15px;
宽度:200px;
高度:50px;
线高:50px;
边框宽度:1px;
字体大小:20px;
文本对齐:居中;
}
iframe
{
显示:无;
}

维蒂康



从…转换。。 美元 阿根廷比索 澳元 巴林第纳尔 博茨瓦纳普拉 巴西雷亚尔 文莱元 保加利亚列夫 加元 智利的智利比索 人民币 哥伦比亚比索 克罗地亚库那 捷克克朗 丹麦克朗 欧元 香港元 福林 冰岛克朗 印度卢比 印尼盾 伊朗里亚尔 以色列谢克尔 日元 哈萨克斯坦坚戈 韩元 科威特第纳尔 利比亚第纳尔 马来西亚吉特 毛里求斯卢比 墨西哥比索 尼泊尔卢比 新西兰元 挪威克朗 阿曼里亚尔 巴基斯坦卢比 菲律宾比索 波兰兹罗提 卡塔尔里亚尔 罗马尼亚新列伊 卢布 沙特阿拉伯里亚尔 新加坡元 南非兰特 斯里兰卡卢比 瑞典克朗 瑞士法郎 新台币 泰铢 特立尼达元 土耳其里拉 迪拉姆酋长国 英镑 委內瑞拉博利瓦 到 转换为。。 美元 阿根廷比索 澳元 巴林第纳尔 博茨瓦纳普拉 巴西雷亚尔 文莱元 保加利亚列夫 加元 智利的智利比索 人民币 哥伦比亚比索 克罗地亚库那 捷克克朗 丹麦克朗 欧元 香港元 福林 冰岛克朗 印度卢比 印尼盾 伊朗里亚尔 以色列谢克尔 日元 哈萨克斯坦坚戈 韩元 科威特第纳尔 利比亚第纳尔 马来西亚吉特 毛里求斯卢比 墨西哥比索 尼泊尔卢比 新西兰元 挪威克朗 阿曼里亚尔 巴基斯坦卢比 菲律宾比索 波兰兹罗提 卡塔尔里亚尔 罗马尼亚新列伊 卢布 沙特阿拉伯里亚尔 新加坡元 南非兰特 斯里兰卡卢比 瑞典克朗 瑞士法郎 新台币 泰铢 特立尼达元 土耳其里拉 迪拉姆酋长国 英镑 委內瑞拉博利瓦

转换



函数变量(){ var select1=document.getElementById('From'); var From=(select1.options[select.selectedIndex]); var select2=document.getElementById('To'); var To=(select2.options[select.selectedIndex]); } 函数警报(){ 警报(从.value+到.value) 警报(document.getElementById('amount').value) }
有许多库可以实现这一点。我在公司使用的是

编辑:添加示例。这是一个精简版的实用程序函数,它接收一个文件和一组属性,将excel工作表中的数据解析为更可用的形式

var REGEX = { 'regexExcel': /^.+\.(xlsx?)$/i, 'regexExcelWithOds: /^.+\.((?:xlsx?)|(?:ods))$/i };

/**
 * Converts an excel column letter (e.g. R, AZ) to an associated integer
 * value so that it can be used as an iterator
 **/
function excelColumnToInt (index)
{
  var multiplier = 1, value = 0;

  for (var iterator = (index.length - 1); iterator >= 0; iterator--)
  {
    if (multiplier === 1)
    {
      //'A' is 65 in ASCII. It equates to 0 for our purposes.
      value += (index.charCodeAt (iterator) - 65);
    }
    else
    {
      value += (index.charCodeAt (iterator) - 64) * multiplier;
    }

    multiplier *= 26;
  }

  return value;
}

/**
 * Retrieves the letter of the column associated with the given field name
 **/
function excelGetColumnForProperty (worksheet, fieldName, bounds)
{
  var column;

  for (var count = bounds[0].c; count <= bounds[1].c; count++)
  {
    column = excelIntToColumn(count);

    try
    {
      if (worksheet[column + bounds[0].r].v.trim ().toLowerCase () === fieldName.toLowerCase ())
      {
        return column;
      }
    }
    catch (exception)
    {
      continue;
    }
  }

  return null;
}

/**
 * Validates a given excel document against its given fields, then feeds the
 * result to the given callback function
 **/
function importFromExcel (filepicker, properties, callback)
{
  var processing = true;

  var files = $(filepicker)[0].files;

  if (!files.length)
  {
    //Raise error notification here

    processing = false;

    return;
  }

  if (!properties || !properties.length)
  {
    processing = false;

    return;
  }

  var errorMessage;
  var errorList = [], itemSet = [];
  var workbook, extensionCheck;
  var reader = new FileReader ();

  //Handler is created before iterating through the files
  reader.onload = function (event)
  {
    try
    {
      switch (extensionCheck[1])
      {
        case 'xls':
          workbook = XLS.read (event.target.result, {type: 'binary'});

          break;
        case 'ods':
          //NOTE: Has some issues with parsing sparse sheets
          workbook = XLSX.read (event.target.result, {type: 'binary'});

          break;
        default:
          workbook = XLSX.read (event.target.result, {type: 'binary'});
      }
    }
    catch (exception)
    {
      //Raise error notification here

      processing = false;

      return;
    }

    var sheet, ref, bounds, tmp, count, match;

    workbook.SheetNames.forEach (function (sheetname, sheetIndex)
    {
      sheet = workbook.Sheets[sheetname];

      //Skip empty worksheets
      if (!sheet['!ref']) { return; }

      //Format: A1:ZZ99
      ref = sheet['!ref'].split (':');
      bounds = [];

      //Low bound
      tmp = ref[0].match (/^([A-Z]+)([0-9]+)$/);
      bounds[0] = {c: excelColumnToInt (tmp[1]), r: parseInt(tmp[2])};

      //High bound
      tmp = ref[1].match (/^([A-Z]+)([0-9]+)$/);
      bounds[1] = {c: excelColumnToInt (tmp[1]), r: parseInt(tmp[2])};

      //Cycle through the last row. If content is not found, reduce the
      //bound and try the next row up
      var checkingBounds = true;

      while (checkingBounds)
      {
        for (count = 0; count < bounds[1].c; count++)
        {
          try
          {
            if (!!sheet[excelIntToColumn (count) + bounds[1].r].w)
            {
              checkingBounds = false;
              bounds[1].r++;
              break;
            }
          }
          catch (exception)
          {
            //Fail silently
          }
        }

        bounds[1].r--;
      }

      //Find the column associated with each property
      properties.forEach (function (property, propertyIndex)
      {
        property.column = excelGetColumnForProperty (sheet, property.name, bounds);

        //Column with the given name not found
        if (!property.column)
        {
          errorList.push ('Could not find a column corresponding to <strong>' + property.name + '</strong> on <strong>' + sheetname + '</strong>');
        }
      });

      if (!!errorList.length) { return; }

      //Retrieve product data
      var itemObj;
      var rowValid = true;

      for (count = (bounds[0].r + 1); count <= bounds[1].r; count++)
      {
        itemObj = {};
        rowValid = true;

        properties.forEach (function (property, propertyIndex)
        {
          try
          {
            if (property.required && sheet[property.column + count] === undefined)
            {
              throw 'Required property missing';
            }

            //Define custom handlers based on expected inputs
            switch (property.handler)
            {
              case 'myHandler':

                break;
              default:
                itemObj[property.field] = sheet[property.column + count].v;
            }
          }
          catch (exception)
          {
            //Guard in case the flattened sheet is missing an index associated with an optional value
            if (exception === 'Required property missing' && property.required)
            {
              errorList.push ('Could not find a value for <strong>' + property.name + '</strong> on <strong>' + sheetname + '</strong> at <strong>row ' + count + '</strong>. This is a required field.');
              rowValid = false;
            }
          }
        });

        if (rowValid)
        {
          itemSet.push (itemObj);
        }
      }
    });

    if (!!errorList.length)
    {
      errorMessage = '<p>The system encountered issues when trying to read your file. Please fix these problems before proceeding.</p><ul>';

      errorList.forEach (function (error, index)
      {
        errorMessage += '<li>' + error + '</li>';
      });

      errorMessage += '</ul>';

      //Notify user of the errors you encountered here

      processing = false;
    }
    else
    {
      callback (itemSet);
    }
  };

  var count, file;

  //Note: Only one file is supported at this time, but the structure
  //      for handling multiple files is the same. Support for multiple
  //      files results in a fairly complicated synchronization model.
  for (count = 0; count < files.length; count++)
  {
    file = files[count];

    extensionCheck = file.name.match (REGEX.regexExcel);

    if (!extensionCheck)
    {
      //ODS files don't seem to parse correctly
      errorList.push ('The file ' + file.name + ' is invalid. Please provide a .xls or a .xlsx file.');

      continue;
    }

    reader.readAsBinaryString (file);
  }

  if (!!errorList.length)
  {
    errorMessage = '<p>The system encountered issues when trying to read your file. Please fix these problems before proceeding.</p><ul>';

    errorList.forEach (function (error, index)
    {
      errorMessage += '<li>' + error + '</li>';
    });

    errorMessage += '</ul>';

    //Notify user of parsing errors here

    processing = false;
  }
}

你能解释一下如何使用它吗?事实上,这并不重要,我试着使用它,但数据没有出现。我认为这是因为文档中的web数据..添加了一个相当全面的示例。主要的限制是列标题必须位于电子表格的第一行,但它们可以是任何顺序,并且每个标题都可以有一个唯一的处理程序
importFromExcel ('#myFilePicker',
                 [
                   {field: 'name', name: 'Name', handler: 'assignment', required: true},
                   {field: 'is_taxed', name: 'Taxable (Y/N)', handler: 'boolean', required: false}
                 ],
                 function (results)
                 {
                   //Handle the response here
                 });