A code sample that reads the contents of a local Excel file through Javascript

  • 2020-03-30 02:33:32
  • OfStack

Javascript code to read the contents of the local Excel file:


<script type="text/javascript">
function read_excel(){
    var filePath="D:abcd9.com.xls"; //XLS to read
    var sheet_id=2; //Read the second table
    var row_start=3; //Read from line 3
    var tempStr='';
    try{
        var oXL = new ActiveXObject("Excel.application"); //Create the Excel.Application object
    }catch(err)
    {
        alert(err);
    }
    var oWB = oXL.Workbooks.open(filePath);
    oWB.worksheets(sheet_id).select();
    var oSheet = oWB.ActiveSheet;
    var colcount=oXL.Worksheets(sheet_id).UsedRange.Cells.Rows.Count ;
    for(var i=row_start;i<=colcount;i++){
        if (typeof(oSheet.Cells(i,8).value)=='date'){ //The read problem when dealing with the column 8 section of the cell content is the date format
            d= new Date(oSheet.Cells(i,8).value);
            temp_time=d.getFullYear()+"-"+(d.getMonth() + 1)+"-"+d.getDate();
        }
        else
            temp_time=$.trim(oSheet.Cells(i,7).value.toString());
        tempStr+=($.trim(oSheet.Cells(i,2).value)+" "+$.trim(oSheet.Cells(i,4).value)+" "+$.trim(oSheet.Cells(i,6).value.toString())+" "+temp_time+"n");
        //Read the contents of columns 2, 4, 6, and 8
    }
    return tempStr; // return 
    oXL.Quit();
    CollectGarbage();
}
</script>

 

Requirements:

1, the client must install the Microsoft Excel activex control (install the full version of Microsoft office), and in the browser pop-up "this website needs to run the following add-on......" Is allowed to run when prompted, otherwise the js code will make an error when creating the Excel.Application object.
2. JS reading local Excel files involves security issues, and Microsoft Excel activex control has no execution permission under default Settings. The solution is as follows:
A. click the browser "tools" -> "Internet options" -> "Secure", select "trusted site".
B. Click the "site (S)" button to add the website to the list;
C. Click "custom level (c)..." , under the "ActiveX control and plug-in" node in the security Settings, find "initialize and execute scripts for ActiveX controls that are not marked as safe to execute scripts" and set it to "enable".


Related articles: