C#讀取excel檔案,產生json

來源:互聯網
上載者:User

標籤:blank   管理系   int   end   title   安裝完成   var   個數   noi   

這段時間在做一個資料管理系統,需要讀取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             finally31             {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的內容。

 

C#讀取excel檔案,產生json

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.