Excel動態生成JSON

2022-03-07 09:38:53 字數 2472 閱讀 6740

在最近的乙個專案中,有大量的資料來源來至excel,轉成json供前台使用。excel資料是人工錄入的,難免會有錯誤,所以中間會有邏輯檢查。在c#中

讀取excel

的方式有很多,網上一搜一大堆,這裡我也貼出乙個excelhelper,提供根據excel檔案獲取所有sheet名稱和獲取sheet內容兩個方法。使用的時候記得註冊

accessdatabaseengine

,該驅動有64位、32位兩個版本,請根據自己的環境選擇正確的版本。

using

system;

using

system.collections.generic;

using

system.data;

using

system.data.oledb;

using

system.linq;

namespace

math.library.helper

;extended properties='excel 12.0;hdr=no;imex=1;'

", filepath);

string commandstring = string.format("

select * from [$]

", sheetname);

using (oledbconnection connection = new

oledbconnection(connectionstring))

table.rows.removeat(0);

return

table;}}

}public

static list getexcelsheetnames(string

filepath)

;extended properties='excel 12.0;hdr=yes;imex=1;'

", filepath);

connection = new

oledbconnection(connectionstring);

connection.open();

dt = connection.getoledbschematable(oledbschemaguid.tables, null

);

if (dt == null

)

string excelsheets = new

string[dt.rows.count];

int i = 0

;

foreach (datarow row in

dt.rows)

return

excelsheets.distinct().tolist();

}catch

(exception ex)

finally

if (dt != null

) }}

}}

假如我的excel資料如下,有班級和學生兩張表(實際上有上百個sheet,這裡只做演示之用)。

當然我們不可能為每乙個sheet都對應做乙個資料model,不僅繁瑣,還很容易出錯。這時我想到了

newtonsoft.json

,newtonsoft.json是.net下開源的json格式序列化和反序列化的類庫。其中

newtonsoft.json.linq

提供了對linq支援,支援動態物件、陣列的序列化。

將整個excel轉換為乙個json檔案,每乙個sheet name作為key,content就是value,value以陣列形式存在,最終得到資料格式如下:

對應的**如下,jarray和jobject是newtonsoft.json中的物件,支援動態屬性和方法,表名和列名就是這樣插入json中的。

class

program

table.add(row);

}json.add(tablename, table);

});console.writeline(json.tostring());

console.writeline(json.tostring(formatting.none));

}static

void main(string

args)

}

當然,為了減少前後端傳輸資料的流量,可以使用tostring(formatting.none),這樣生成出來的資料就沒有格式了。

動態生成excel

20gp的合併運費,補錄費用,箱號 iteratorit list.iterator 20gp箱子數量 int twetygp 0 臨時箱號 string tempcontainerno 臨時運費 bigdecimal yf new bigdecimal 0 需要刪除箱子的臨時id string t...

C 讀取excel檔案,生成json

這段時間在做乙個資料管理系統,需要讀取excel 組裝json,最終存入mongodb,這裡記錄一下解決思路。需要做的準備工作 1.安裝accessdatabaseengine 有32bit和64bit兩個版本,具體要安裝哪個要看你的office程式是32bit的還是64bit的。通常來講,一般是選...

C 讀取excel檔案,生成json

這段時間在做乙個資料管理系統,需要讀取excel 組裝json,最終存入mongodb,這裡記錄一下解決思路。需要做的準備工作 1.安裝accessdatabaseengine 有32bit和64bit兩個版本,具體要安裝哪個要看你的office程式是32bit的還是64bit的。通常來講,一般是選...