我做了一个货币转换器并且我将所有货币汇率放在.xlsx(excel文件)中,数据正在更新并自动保存,因此我无法将其保存为.csv并将数据解析到脚本中。我需要知道如何直接从excel获取数据到JavaScript(我只能在javascript中理解,所以如果你使用其他语言,我会很高兴,如果你发送完整的代码)。
这是网站本身:
header
{
position: fixed;
width: 100%;
top: 0;
background-image: url(../images/banner-1103703_960_720.jpg);
box-shadow: 0 0 4px grey;
}
body
{
margin: 0px;
background-color: #6eaac4;
}
#converter
{
padding-top: 230px;
text-align: center;
}
#logo
{
max-width: 340px;
}
#to
{
font-size: 40px;
color: firebrick;
font-family:fantasy;
}
select
{
width: 300px;
height: 50px;
line-height: 50px;
border-radius: 15px;
background-color:lightblue;
font-size: 20px;
}
article
{
background-color: chartreuse;
border-radius: 50px;
border-color: black;
width: 340px;
height: auto;
}
button
{
/* Green */
background-color:whitesmoke;
background-repeat:no-repeat;
border: 4px;
cursor:pointer;
overflow: hidden;
border-radius: 30px;
outline:none;
color: firebrick;
text-align: center;
font-family: fantasy;
letter-spacing: 5px;
text-decoration: none;
font-size: 50px;
}
input
{
background-color: lightblue;
border-radius: 15px;
width: 200px;
height: 50px;
line-height: 50px;
border-width: 1px;
font-size: 20px;
text-align: center;
}
iframe
{
display: none;
}
<!DOCTYPE html>
<html manifest="offline.manifest">
<head>
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="design/style.css">
<link rel="icon" href="images/icon.ico">
<title>Vertycon</title>
<script src="jquery-3.1.0.min.js" ></script>
</head>
<body onload="">
<header>
<center><a href="index.html">
<img id="logo" src="images/LOGO.png" height="170px" width="340px">
</a></center> </header>
<div id="converter">
<center> <article><br>
<input type="number" name="amount" placeholder="Amount" id="amount"/>
<br><br>
<select id="From">
<option value="Display">Convert From..</option>
<option value="US Dollar">US Dollar</option>
<option value="ARS"> Argentine Peso</option>
<option value="AUD">Australian Dollar</option>
<option value="BHD">Bahraini Dinar</option>
<option value="BWP">Botswana Pula</option>
<option value="BRL">Brazilian Real</option>
<option value="BND">Bruneian Dollar</option>
<option value="BGN">Bulgarian Lev</option>
<option value="CAD">Canadian Dollar</option>
<option value="CLP">Chilean Peso</option>
<option value="CNY">Chinese Yuan Renminbi</option>
<option value="COP">Colombian Peso</option>
<option value="HRK">Croatian Kuna</option>
<option value="CZK">Czech Koruna</option>
<option value="DKK">Danish Krone</option>
<option value="EUR">Euro</option>
<option value="HKD">Hong Kong Dollar</option>
<option value="HUF">Hungarian Forint</option>
<option value="ISK">Icelandic Krona</option>
<option value="INR">Indian Rupee</option>
<option value="IDR">Indonesian Rupiah</option>
<option value="IRR">Iranian Rial</option>
<option value="ILS">Israeli Shekel</option>
<option value="JPY">Japanese Yen</option>
<option value="KZT">Kazakhstani Tenge</option>
<option value="KRW">South Korean Won</option>
<option value="KWD">Kuwaiti Dinar</option>
<option value="LYD">Libyan Dinar</option>
<option value="MYR">Malaysian Ringgit</option>
<option value="MUR">Mauritian Rupee</option>
<option value="MXN">Mexican Peso</option>
<option value="NPR">Nepalese Rupee</option>
<option value="NZD">New Zealand Dollar</option>
<option value="NOK">Norwegian Krone</option>
<option value="OMR">Omani Rial</option>
<option value="PKR">Pakistani Rupee</option>
<option value="JPY">Philippine Peso</option>
<option value="PLN">Polish Zloty</option>
<option value="QAR">Qatari Riyal</option>
<option value="RON">Romanian New Leu</option>
<option value="RUB">Russian Ruble</option>
<option value="SAR">Saudi Arabian Riyal</option>
<option value="SGD">Singapore Dollar</option>
<option value="ZAR">South African Rand</option>
<option value="LKR">Sri Lankan Rupee</option>
<option value="SEK">Swedish Krona</option>
<option value="CHF">Swiss Franc</option>
<option value="TWD">Taiwan New Dollar</option>
<option value="THB">Thai Baht</option>
<option value="TTD">Trinidadian Dollar</option>
<option value="TRY">Turkish Lira</option>
<option value="AED">Emirati Dirham</option>
<option value="GBP">British Pound</option>
<option value="VEF">Venezuelan Bolivar</option>
</select>
<div id="to"> To </div>
<select id="To">
<option value="Display">Convert To..</option>
<option value="USD">US Dollar</option>
<option value="ARS"> Argentine Peso</option>
<option value="AUD">Australian Dollar</option>
<option value="BHD">Bahraini Dinar</option>
<option value="BWP">Botswana Pula</option>
<option value="BRL">Brazilian Real</option>
<option value="BND">Bruneian Dollar</option>
<option value="BGN">Bulgarian Lev</option>
<option value="CAD">Canadian Dollar</option>
<option value="CLP">Chilean Peso</option>
<option value="CNY">Chinese Yuan Renminbi</option>
<option value="COP">Colombian Peso</option>
<option value="HRK">Croatian Kuna</option>
<option value="CZK">Czech Koruna</option>
<option value="DKK">Danish Krone</option>
<option value="EUR">Euro</option>
<option value="HKD">Hong Kong Dollar</option>
<option value="HUF">Hungarian Forint</option>
<option value="ISK">Icelandic Krona</option>
<option value="INR">Indian Rupee</option>
<option value="IDR">Indonesian Rupiah</option>
<option value="IRR">Iranian Rial</option>
<option value="ILS">Israeli Shekel</option>
<option value="JPY">Japanese Yen</option>
<option value="KZT">Kazakhstani Tenge</option>
<option value="KRW">South Korean Won</option>
<option value="KWD">Kuwaiti Dinar</option>
<option value="LYD">Libyan Dinar</option>
<option value="MYR">Malaysian Ringgit</option>
<option value="MUR">Mauritian Rupee</option>
<option value="MXN">Mexican Peso</option>
<option value="NPR">Nepalese Rupee</option>
<option value="NZD">New Zealand Dollar</option>
<option value="NOK">Norwegian Krone</option>
<option value="OMR">Omani Rial</option>
<option value="PKR">Pakistani Rupee</option>
<option value="JPY">Philippine Peso</option>
<option value="PLN">Polish Zloty</option>
<option value="QAR">Qatari Riyal</option>
<option value="RON">Romanian New Leu</option>
<option value="RUB">Russian Ruble</option>
<option value="SAR">Saudi Arabian Riyal</option>
<option value="SGD">Singapore Dollar</option>
<option value="ZAR">South African Rand</option>
<option value="LKR">Sri Lankan Rupee</option>
<option value="SEK">Swedish Krona</option>
<option value="CHF">Swiss Franc</option>
<option value="TWD">Taiwan New Dollar</option>
<option value="THB">Thai Baht</option>
<option value="TTD">Trinidadian Dollar</option>
<option value="TRY">Turkish Lira</option>
<option value="AED">Emirati Dirham</option>
<option value="GBP">British Pound</option>
<option value="VEF">Venezuelan Bolivar</option>
</select>
<br>
<br>
<button type="submit" id="submit" onclick="Vars; Alert();">Convert!</button>
<br>
<br>
<br>
<br>
</article></center>
</div>
<iframe src="https://onedrive.live.com/embed?cid=BE27105A8171337A&resid=BE27105A8171337A%211291&authkey=ALjfySLkSxTD7MU&em=2" width="402" height="346" frameborder="0" scrolling="no" id="ifrm"></iframe>
<script>
function Vars(){
var select1 = document.getElementById('From');
var From = (select1.options[select.selectedIndex]);
var select2 = document.getElementById('To');
var To = (select2.options[select.selectedIndex]);
}
function Alert(){
alert(From.value+To.value)
alert(document.getElementById('amount').value)
}
</script>
</body>
</html>
这是excel文件:
先谢谢了, 爱你们的人
答案 0 :(得分:0)
有许多库可以实现这一目标。我用过公司的那个是SheetJS。
编辑:添加一个例子。这是实用程序函数的精简版本,它接受一个文件和一组属性,以将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;
}
}
使用示例:
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
});