将 Excel 解析为 JSON

问题描述 投票:0回答:3

我想知道是否可以将 excel 解析为 json。 如果可能的话,Excel 的结构使其成为可能。 有申请什么的吗??

我有这个 JSON 结构 http://pastie.org/2760828 我必须插入 500 个产品,我想插入到 Excel 中并解析它们。

json excel parsing
3个回答
6
投票

你可以这样做:
1)首先将 Excelsheet 转换为数据表
2) 然后将数据表转换为 json,如下所示:

1)将Excel表转换为数据表

string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=G:\school pro\schools3.xlsx;
Extended Properties=Excel 5.0";

StringBuilder stbQuery = new StringBuilder();
stbQuery.Append("SELECT top 10 * FROM [A1:M98]");
OleDbDataAdapter adp = new OleDbDataAdapter(stbQuery.ToString(), ConnectionString);

DataTable dtSchools = new DataTable();
adp.Fill(dtSchools);

2)将数据表转换为json

Newtonsoft.Json.JsonConvert.SerializeObject(dtSchools)

0
投票

最近Excel有一个代码编辑器插件,可以像宏一样使用。 这张桌子

可以转换成这个json

[
    { "Group": "A", "Name": "John", "Age": "21" },
    { "Group": "B", "Name": "Tim", "Age": "24" },
    { "Group": "A", "Name": "Jane", "Age": "28" },
    { "Group": "B", "Name": "Monica", "Age": "26"}
]

使用此界面

interface TableData {
    "Group": string;
    "Name": string;
    "Age": string;
}

还有这个代码

function main(workbook: ExcelScript.Workbook): TableData[] {


    // Get the current, active worksheet and used cells.
    let currentWorksheet = workbook.getActiveWorksheet();    
    let usedRange = currentWorksheet.getUsedRange();    
    console.log(usedRange.getAddress()); // log range address
    // get text
    const texts = usedRange.getTexts();
    // Create an array of JSON objects that match the row structure.
    let returnObjects: TableData[] = [];
    if (usedRange.getRowCount() > 0) {
        returnObjects = returnObjectFromValues(texts);
    }
    // console.log(returnObjects)
    // Log the information and return it for a Power Automate flow.
    console.log(JSON.stringify(returnObjects));
    return returnObjects;
}

上面我们使用了辅助函数

returnObjectFromValues()


// function converts 2D array of values into a generic JSON object
// here with TableData object, but any similar interface would work.
function returnObjectFromValues(values: string[][]): TableData[] {
    let objectArray: TableData[] = [];
    let objectKeys: string[] = [];
    for (let i = 0; i < values.length; i++) {
        if (i === 0) {
            objectKeys = values[i];
            continue;
        }

        let object = {};
        for (let j = 0; j < values[i].length; j++) {
            object[objectKeys[j]] = values[i][j];
        }

        objectArray.push(object as TableData);
    }

    return objectArray;
}

这可以在 sqlite 中进行分析;-)

SELECT     
    json_extract(jsonEach.value, '$.Group') as GroupName,
    json_extract(jsonEach.Value, '$.Name') as UserName,
    json_extract(jsonEach.Value, '$.Age') as Age,
    jsonEach.Value as Json_Array_Element
    FROM UserGroup,json_each(UserGroup.JsonArray, '$') as jsonEach; 

结果看起来像这样


-2
投票

ExcelToJSON 将 Excel 工作表转换为 JSON 格式

http://www.exceltojson.com/

© www.soinside.com 2019 - 2024. All rights reserved.