Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read the excel file from the directory not from the address that you given

I am using html5 and javascript. I want to read the Excel file which is chosen by the user from the directory (using a file dialog) but all I know is to read an excel file by the given path:

function readdata(y,x) {
    try {
        var excel = new ActiveXObject("Excel.Application");
        excel.Visible = false;
        var excel_file = excel.Workbooks.Open("D:\\Test.xls");
        //  alert(excel_file.worksheets.count);
        var excel_sheet = excel_file.Worksheets("Sheet1");
        var data = excel_sheet.Cells(x, y).Value;
        //alert(data);
        drawWithexcelValue(data);
    }
    catch (ex) {
        alert(ex);
    }
    return data;
}

This is what I have to read the excel file. Can any one help me to read a file by directory, or without giving the path of the file. I would also like to know how to show output from that.

Thanx in advance

like image 442
user2502227 Avatar asked Nov 03 '22 19:11

user2502227


1 Answers

Try the following code, it is a bit of a hack and it seems to work with IE7. However, it will not work with other browsers because they will not show the file path. Other browsers will also never be able to show the ActiveXObject (Excel).

<!DOCTYPE html>
<html>
<head>
<body>
<div id="divHidden" style="visibility: hidden; width: 0px; height: 0px">
  <input type=file id="fileInput">
</div>
<input type=button value="click here to get a file" onclick="readdata(1,1);">

<script language=javascript>

    function readdata(y,x) {

        // Use the <input type='file'...> object to get a filename without showing the object.
        document.all["fileInput"].click();
        var fileName = document.all["fileInput"].value;

        try {
            var excel = new ActiveXObject("Excel.Application");
            excel.Visible = false;
            var excel_file = excel.Workbooks.Open(fileName);

            var excel_sheet = excel_file.Worksheets("Sheet1");
            //  var data = excel_sheet.Cells(x, y).Value;
            var data;
            for (; excel_sheet.Cells(x, y).Value.length > 0; x++){
                data[i][0] = excel_sheet.Cells(x, y).Value;
                data[i][1] = excel_sheet.Cells(x, y+1).Value;
            }
            drawWithexcelValue(data);
        }
        catch (ex) {
            alert(ex);
        }

        // This will show the data.
        alert(data);

    }

</script>
</body>
</html>
like image 165
psiphi75 Avatar answered Nov 09 '22 16:11

psiphi75