从Excel中读取数据到C#中的Json对象

我有一个Excel工作表,它有一组列和数据的行。 我想读完整的Excel工作表数据为JSON,以便以后我可以将JSON写入一个文件。 我怎样才能做到这一点?

样本数据:

Names RegNo Description ABCD 12345 DemoInfo XYZ 67890 DemoInfo2 

通过ADO.NET OleDb提供程序连接到Excel工作表。 然后,使用C#的JSON库生成JSONstring,并保存该文件。 (或使用JavascriptSerialzer,如@boadesbuild议)。

这个例子使用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); } } } } } 

链接:

  • 在ADO.NET中检索和修改数据 – 如何使用连接,命令和阅读器
  • Excel 2007连接string
  • “OLEDB提供者”部分下的较旧的Excel连接string
  • 用于C#的JSON库可以在JSON页面上find
  • JSON.NET
  • Microsoft Access数据库引擎2010可再发行组件 ,如果您没有安装Excel 2007+

你可以尝试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); } } 

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