从excel读取数据到c#中的Json对象

cha*_*duH 5 c# excel json

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

样本数据:

Names    RegNo    Description
ABCD     12345    DemoInfo
XYZ      67890    DemoInfo2
Run Code Online (Sandbox Code Playgroud)

Zev*_*itz 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 = $@"
                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);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

链接:

  • 请注意,您不需要安装Excel,只需下载Microsoft Access数据库引擎可再发行组件,此时可在此处获取:http://www.microsoft.com/en-gb/download/details.aspx?id = 13255 (2认同)

tre*_*het 2

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