[A method to use a browser to read local excel, josn and other data files] Python+JavaScript+HTML implementation

1. Background

Generally speaking, for the sake of network access security, browsers cannot directly load local files. IE-based browsers provide the AX control to read local files. Chrome 86 and later versions also provide corresponding APIs, but they all exist. Limitations and compatibility issues. Sometimes developers just want to use the browser to compile some simple scripts to complete some tasks, and don't want to learn C, C++, and Python to generate exes 例如使用JavaScript脚本读取本地一个excel文件进行统计分析. But due to the limitation that the browser cannot use local files, I had to give up. This article discusses a method 非IE内核浏览器读取本地excel数据的方法to circumvent this limitation.

In order to achieve this goal, Python, JavaScript, json, HTML and other knowledge are used. At the same time, bloggers also found this solution by studying other articles.

For related articles, please see:
https://blog.csdn.net/qq_41581588/article/details/129681572
https://blog.csdn.net/qq_30337695/article/details/51788007

2. Solution ideas

把本地文件的数据转换为json格式数据
.js文件将通过script标签插入HTML文件
1.使用python读取本地文件
2.把json格式数据保存为.js文件
3.使用python在HTML文件头中写入.js文件,编写读取.js文件json数据的JavaScript代码
4.使用python打开浏览器加载对应的HTML文件

The solution to the problem is as follows:

  1. Use python to read local files and convert them to .js files in json format;
  2. Use tags in the HTML file header <script>to introduce the converted .js data file;
  3. Use python to open the browser and load the corresponding HTML file.

3. Specific implementation

(1) Use python to read local files and convert them to .js files in json format

Here we refer to the python code on the Internet for reading local files. We have read excel as an example. We used the json library and xlrd2 library to write a .js file that reads a single excel file and converts it into json data format. Among 参数paththem 待读取的excel文件路径, 参数namefor 转换后保存的.js文件名. The main code is as follows:

import os
import json
import xlrd2
import excel2json
import webbrowser

fileTypeArray = [".xlsx", ".xls"]
def readExecl(path, name):
    print(path)
    workbook = xlrd2.open_workbook(path)
    sheet2_name = workbook.sheet_names()[0]
    sheet = workbook.sheet_by_name(sheet2_name)  
    # sheet索引从0开始
    # sheet的名称,行数,列数
    # print sheet.name,sheet.nrows,sheet.ncols

    adict = {
    
    }

    for i in range(1, sheet.nrows):
        data = {
    
    }
        for j in range(0, sheet.ncols):
            value = TransformationType(sheet.cell_value(i, j))
            if isinstance(value, str):
                if isJsonString(value):
                    data[TransformationType(sheet.cell_value(0, j))] = eval(value)
                else:
                    data[TransformationType(sheet.cell_value(0, j))] = value
            else:
                data[TransformationType(sheet.cell_value(0, j))] = value
            adict[TransformationType(sheet.cell_value(i, 0))] = data

    data = json.dumps(adict, indent=1, ensure_ascii=False)
    excel_data = "data = " + data
    _json_save_path = os.getcwd() + "/" + name + '.js'
    f = open(_json_save_path, 'w', encoding='utf-8')
    f.write(excel_data)
    f.close()
    print("already create json:" + path)
    return data, _json_save_path

def isJsonString(str):
    try:
        eval(str)
    except Exception as e:
        return False
    return True


def TransformationType(var):
    if isinstance(var, float):  # type(var) == 'float':
        str1 = int(var)
    elif isinstance(var, str):  # type(var) == 'unicode':
        str1 = var
    else:
        raise Exception("type is not deal")
        str1 = var
    return str1

Then compile the run function to test the above code, read the current 题库.xlsfile, and output excel_data.jsthe file. The run function code is as follows:

def run():
    _file_path = os.getcwd() + "/" + "题库.xls"
    _filename = os.path.basename(_file_path)
    _json_data = excel2json.readExecl(_file_path, "excel_data")

if __name__ == '__main__':
    run()

The running results are as follows, 题库.xlsconverted into excel_data.js.

Insert image description here

Open 题库.xlsand excel_data.js, you can see that each row in excel is converted into json object data.

Insert image description here

(2) Use tags in the HTML file header <script>to introduce the converted .js data file

With that .js文件, you can use tags in the HTML file header <script>to introduce the converted .js data file, which is src="excel_data.js"achieved here by using. The specific code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>读取excel</title>
    <script type="text/javascript" src="excel_data.js"></script>
</head>
<body>
    <script type="text/javascript">
      let data_list = Object.values(data)
	  data_len = data_list.length
	  console.log(data_list)
	  console.log(data_len)
    </script>
</body>
</html>

The browser output is as follows. All the excel data is printed to the console, which proves that the local excel file is successfully read. The excel data can be counted and displayed according to the requirements.

Insert image description here

(3) Use python to open the browser and load the corresponding HTML file

The last step is to automate the two steps just now. Use python to automatically convert excel into a .js file, and call the local browser to open the corresponding HTML to automate the entire process. The specific code is as follows:

def run():
    _file_path = os.getcwd() + "/" + "题库.xls"
    _filename = os.path.basename(_file_path)
    _json_data = excel2json.readExecl(_file_path, "excel_data")
    _url = os.getcwd() + "/" + "index.html"
    webbrowser.open(_url)

if __name__ == '__main__':
    run()

4. Summary

There are actually many ways to use a browser to read local files, including using technologies such as Node.js and Electron framework, but these are somewhat difficult and technically demanding to use. This article uses simple Python+JavaScript+HTML technology to achieve some of the requirements. The needs of small scenes. The complete code is as follows:

Download address: [A method of using a browser to read local excel, josn and other data files] Python+JavaScript+HTML implementation

In addition, the original blogger made an exam question brushing tool based on the IE kernel, and now it has been implemented using this method. It can finally run in various browsers, and there is no need to consider compatibility and other issues.
Download address: A free question brushing tool written in Python+JavaScript+html, which allows the browser to read local excel files and customize the question bank

Guess you like

Origin blog.csdn.net/qq616491978/article/details/132707390