首页 > 解决方案 > Using btoa to parse xls from javascript to C#

问题描述

I have written a program that sends an excel file uploaded by the user from javascript to C# where it is then formatted. The code works well for .xlsx files; however, when I try to parse .xls files, I receive the following error:

System.ArgumentNullException: 'Value cannot be null. Parameter name: s'.

After some further testing with breakpoints, I believe I have found the problem, but I cannot find a solution. The following code is the javascipt used to encode the file:

document.getElementById('selectedFile').addEventListener('change', function (event) {

var reader = new FileReader();
reader.onload = function () {
    filename = event.target.files[0].name;
    var uint8Array = new Uint8Array(this.result);
    fileContent = btoa(String.fromCharCode.apply(null, uint8Array));

}
reader.readAsArrayBuffer(this.files[0]);

}, false);

When the file uploaded is of type .xlsx, fileContent returns the correct value; however, if an .xls file is uploaded, it returns null, therefore breaking the code further on.

Is there a way to make this code work for .xls files? Alternatively, is there a way I can convert it to .xlsx before I parse it to the backend?

标签: javascriptc#excel

解决方案


.xlsx是一种文本格式 (XML),因此String.fromCharCode应该可以正常工作。

.xls是一种二进制文件格式。我希望 String 函数可以正常使用它。

您可以使用 Excel 在格式之间进行转换。转换是不平凡的,虽然不是不可能从 javascript 完成,但可能不值得花几个月的时间。


推荐阅读