【问题标题】:Reading data from excel in to Json object in c#在c#中从excel中读取数据到Json对象
【发布时间】:2012-11-22 21:59:17
【问题描述】:

我有一个 Excel 工作表,其中包含一组包含数据的列和行。我想以 JSON 格式读取完整的 Excel 工作表数据,以便稍后将 JSON 写入文件。我该怎么做?

样本数据:

Names    RegNo    Description
ABCD     12345    DemoInfo
XYZ      67890    DemoInfo2

【问题讨论】:

    标签: c# json excel


    【解决方案1】:

    将其保存为 CSV。然后使用 File.ReadLines 枚举每一行,然后使用 String.Split 读取每一列。将数据格式化为 JSON 字符串并将其保存到文件中。

    【讨论】:

      【解决方案2】:

      通过 ADO.NET OleDb 提供程序连接到 Excel 工作表。然后,使用 C# 的 JSON 库生成 JSON 字符串,并保存文件。 (或者按照@boades 的建议使用 JavascriptSerialzer)。

      此示例使用 JSON.NET 库。

      using System;
      using System.Linq;
      using System.Data.OleDb;
      using System.Data.Common;
      using Newtonsoft.Json;
      using System.IO;
      
      namespace ConsoleApplication1 {
          class Program {
              static void Main(string[] args) {
                  var pathToExcel = @"C:\path\to\excel\file.xlsx";
                  var sheetName = "NameOfSheet";
                  var destinationPath = @"C:\path\to\save\json\file.json";
      
                  //Use this connection string if you have Office 2007+ drivers installed and 
                  //your data is saved in a .xlsx file
                  var connectionString = $@"
                      Provider=Microsoft.ACE.OLEDB.12.0;
                      Data Source={pathToExcel};
                      Extended Properties=""Excel 12.0 Xml;HDR=YES""
                  ";
      
                  //Creating and opening a data connection to the Excel sheet 
                  using (var conn=new OleDbConnection(connectionString)) {
                      conn.Open();
      
                      var cmd=conn.CreateCommand();
                      cmd.CommandText = $"SELECT * FROM [{sheetName}$]";
      
                      using (var rdr=cmd.ExecuteReader()) {
      
                          //LINQ query - when executed will create anonymous objects for each row
                          var query = rdr.Cast<DbDataRecord>().Select(row => new {
                              name = row[0],
                              regno = row[1],
                              description = row[2]
                          });
      
                          //Generates JSON from the LINQ query
                          var json = JsonConvert.SerializeObject(query);
      
                          //Write the file to the destination path    
                          File.WriteAllText(destinationPath, json);
                      }
                  }
              }
          }
      }
      

      链接:

      【讨论】:

      【解决方案3】:

      你可以试试http://exceldatareader.codeplex.com/库。 您必须从 excel 读取数据到某个对象,然后使用 JavaScriptSerializer 将其转换为 json

      public class MyRow
      {
         public string Cell1;
         public string Cell2;
         public string Cell3;
      }
      
      class Program
      {
              static void Main()
              {
                  var list = new List<MyRow>();
                  FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
      
                  //1. Reading from a binary Excel file ('97-2003 format; *.xls)
                  IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
                  //...
                  //2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
                  IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
      
      
                  //5. Data Reader methods
                  while (excelReader.Read())
                  {
                         var obj = new MyRow 
                         {
                             Cell1 = excelReader.GetString(0),
                             Cell2 = excelReader.GetString(1),
                             Cell3 = excelReader.GetString(2),
                         }
      
                         list.Add(obj);
                  }
      
                  //6. Free resources (IExcelDataReader is IDisposable)
                  excelReader.Close();
                  var json = new JavaScriptSerializer().Serialize(list);
                  Console.WriteLine(json);
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多