C#讀取excel文件,生成json


這段時間在做一個數據管理系統,需要讀取excel表格,組裝json,最終存入mongodb,這里記錄一下解決思路。

需要做的准備工作:

1.安裝AccessDatabaseEngine

 

下載地址:https://products.office.com/zh-cn/compare-all-microsoft-office-products?tab=1

有32bit和64bit兩個版本,具體要安裝哪個要看你的Office程序是32bit的還是64bit的。通常來講,一般是選擇與office程序相對應的版本。但是如果你的項目必須在64位下運行,又不想大費周章刪了原有的office程序再重裝,這時候該咋辦呢?在網上找了很久,終於找到了辦法:

(1)下載AccessDatabaseEngine_x64.exe,放到某一個目錄下,比如:C:\AccessDatabaseEngine_x64.exe,點擊該程序安裝,這個時候會提示你不能安裝,原因是你的office程序是32位的。可選擇其它安裝方式,進入命令窗口,執行

(2)等待安裝完成,查看注冊表HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Common\FilesPaths,刪除mso.dll(此步驟一定要做,查看注冊表:開始-運行-regedit-回車)

2.引用Newtonsoft.Json.dll

下載地址:https://www.newtonsoft.com/json

下載完成后,找到對應版本的dll,項目中直接引用即可。

還有另外一種下載方式,使用Nuget,具體如下:

打開vs工具 - NuGet程序包管理器 - 程序包管理器控制台,這時在VS的底部窗口出現命令行:pm>install-package newtonsoft.json 執行完,會提示下載在哪個位置,再從項目中引用即可。

 

准備工作做好后,就可以開始寫代碼了。

總共三個方法:根據Excel文件獲取所有Sheet名稱,獲取每一個Sheet的內容組裝dataTable,table轉Excel

 (1)根據Excel文件獲取所有Sheet名稱

 1 public List<string> GetExcelSheetNames(string filePath)
 2         {
 3             OleDbConnection connection = null;
 4             System.Data.DataTable dt = null;
 5             try
 6             {
 7                 String connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;IMEX=2;'", filePath);
 8                 connection = new OleDbConnection(connectionString);
 9                 connection.Open();
10                 dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
11 
12                 if (dt == null)
13                 {
14                     return new List<string>();
15                 }
16 
17                 String[] excelSheets = new String[dt.Rows.Count];
18                 int i = 0;
19                 foreach (DataRow row in dt.Rows)
20                 {
21                     excelSheets[i] = row["TABLE_NAME"].ToString().Split('$')[0];
22                     i++;
23                 }
24                 return excelSheets.Distinct().ToList();
25             }
26             catch (Exception ex)
27             {
28                 return new List<string>();
29             }
30             finally
31             {
32                 if (connection != null)
33                 {
34                     connection.Close();
35                     connection.Dispose();
36                 }
37                 if (dt != null)
38                 {
39                     dt.Dispose();
40                 }
41             }
42         }
View Code

(2)獲取每一個Sheet的內容組裝dataTable

 1  public DataTable GetExcelContent(String filePath, string sheetName)
 2         {
 3             if (sheetName == "_xlnm#_FilterDatabase")
 4                 return null;
 5             DataSet dateSet = new DataSet();
 6             String connectionString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=NO;IMEX=2;'", filePath);
 7             String commandString = string.Format("SELECT * FROM [{0}$]", sheetName);
 8             using (OleDbConnection connection = new OleDbConnection(connectionString))
 9             {
10                 connection.Open();
11                 using (OleDbCommand command = new OleDbCommand(commandString, connection))
12                 {
13                     OleDbCommand objCmd = new OleDbCommand(commandString, connection);
14                     OleDbDataAdapter myData = new OleDbDataAdapter(commandString, connection);
15                     myData.Fill(dateSet, sheetName);
16                     DataTable table = dateSet.Tables[sheetName];
17                     for (int i = 0; i < table.Rows[0].ItemArray.Length; i++)
18                     {
19                         var cloumnName = table.Rows[0].ItemArray[i].ToString();
20                         if (!string.IsNullOrEmpty(cloumnName))
21                             table.Columns[i].ColumnName = cloumnName;
22                     }
23                     table.Rows.RemoveAt(0);
24                     return table;
25                 }
26             }
27         }
View Code

(3)table轉Excel

 1  public string ExcelToJson(string filePath)
 2         {
 3             List<string> tableNames = GetExcelSheetNames(filePath);
 4             var json = new JObject();
 5             tableNames.ForEach(tableName =>
 6             {
 7                 var table = new JArray() as dynamic;
 8                 DataTable dataTable = GetExcelContent(filePath, tableName);
 9                 foreach (DataRow dataRow in dataTable.Rows)
10                 {
11                     dynamic row = new JObject();
12                     foreach (DataColumn column in dataTable.Columns)
13                     {
14                         row.Add(column.ColumnName, dataRow[column.ColumnName].ToString());
15                     }
16                     table.Add(row);
17                 }
18                 json.Add(tableName, table);
19             });
20             return json.ToString();
21         }
View Code

最終生成的是json對象,key是sheet名,value是json數組,為每一張sheet的內容。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM