2012-12-05 51 views
5

我有一個Excel工作表,它有一組包含數據的列和行。我想將完整的Excel工作表數據作爲JSON讀取,以便稍後可以將JSON寫入文件。我怎樣才能做到這一點?從excel中讀取數據到JSON對象的c#

的樣本數據:

Names RegNo Description 
ABCD  12345 DemoInfo 
XYZ  67890 DemoInfo2 

回答

1

將它保存爲CSV。然後使用File.ReadLines枚舉每行,然後使用String.Split來讀取每列。將數據格式化爲JSON字符串並將其保存到文件中。

8

通過ADO.NET OleDb提供程序連接到Excel工作表。然後,使用C#的JSON庫生成JSON字符串,並保存該文件。 (或者使用JavascriptSerialzer,建議使用@boades)。

本示例使用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=String.Format(@" 
       Provider=Microsoft.ACE.OLEDB.12.0; 
       Data Source={0}; 
       Extended Properties=""Excel 12.0 Xml;HDR=YES"" 
      ",pathToExcel); 

      //Creating and opening a data connection to the Excel sheet 
      using (var conn=new OleDbConnection(connectionString)) { 
       conn.Open(); 

       var cmd=conn.CreateCommand(); 
       cmd.CommandText = String.Format(
        @"SELECT * FROM [{0}$]", 
        sheetName 
       ); 

       using (var rdr=cmd.ExecuteReader()) { 

        //LINQ query - when executed will create anonymous objects for each row 
        var query = 
         from DbDataRecord row in rdr 
         select 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); 
       } 
      } 
     } 
    } 
} 

鏈接:

+2

請注意,您不需要安裝Excel也爲JSON,你可以下載Microsoft Access數據庫引擎可再發行,這在這個時候是可在這裏:http://www.microsoft.com/en-gb/download/details.aspx?id=13255 – Family

+0

@Family更新,謝謝。 –

2

你可以給一個嘗試http://exceldatareader.codeplex.com/庫。 您必須閱讀從Excel數據到一些對象,並比其轉換使用JavaScriptSerializer

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); 
     } 
    }