Verbinden Sie sich über den ADO.NET OleDb-Anbieter mit dem Excel-Arbeitsblatt. Verwenden Sie anschließend eine JSON-Bibliothek für C#, um die JSON-Zeichenfolge zu generieren, und speichern Sie die Datei. (Oder verwenden Sie den JavascriptSerialzer, wie von @boades vorgeschlagen).
In diesem Beispiel wird die JSON.NET-Bibliothek verwendet.
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);
}
}
}
}
}
Links:
Hinweis JSon, die Sie Excel nicht installiert ist, dann können Sie nur die Microsoft Access-Datenbank-Engine Redistributable herunterladen, die zu diesem Zeitpunkt ist hier verfügbar: http://www.microsoft.com/en-gb/download/details.aspx?id=13255 – Family
@Family aktualisiert, danke. –