using System;
using System.IO;
using System.Data;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace excel2json
{
///
/// 将DataTable对象,转换成JSON string,并保存到文件中
///
class JsonExporter
{
string mContext = "";
int mHeaderRows = 0;
public string context {
get {
return mContext;
}
}
///
/// 构造函数:完成内部数据创建
///
/// ExcelLoader Object
public JsonExporter(ExcelLoader excel, bool lowcase, bool exportArray, string dateFormat, bool forceSheetName, int headerRows, string excludePrefix, bool cellJson)
{
mHeaderRows = headerRows - 1;
List validSheets = new List();
for (int i = 0; i < excel.Sheets.Count; i++)
{
DataTable sheet = excel.Sheets[i];
// 过滤掉包含特定前缀的表单
string sheetName = sheet.TableName;
if (excludePrefix.Length > 0 && sheetName.StartsWith(excludePrefix))
continue;
if (sheet.Columns.Count > 0 && sheet.Rows.Count > 0)
validSheets.Add(sheet);
}
var jsonSettings = new JsonSerializerSettings
{
DateFormatString = dateFormat,
Formatting = Formatting.Indented
};
if (!forceSheetName && validSheets.Count == 1)
{ // single sheet
//-- convert to object
object sheetValue = convertSheet(validSheets[0], exportArray, lowcase, excludePrefix, cellJson);
//-- convert to json string
mContext = JsonConvert.SerializeObject(sheetValue, jsonSettings);
}
else
{ // mutiple sheet
Dictionary data = new Dictionary();
foreach (var sheet in validSheets)
{
object sheetValue = convertSheet(sheet, exportArray, lowcase, excludePrefix, cellJson);
data.Add(sheet.TableName, sheetValue);
}
//-- convert to json string
mContext = JsonConvert.SerializeObject(data, jsonSettings);
}
}
private object convertSheet(DataTable sheet, bool exportArray, bool lowcase, string excludePrefix, bool cellJson)
{
if (exportArray)
return convertSheetToArray(sheet, lowcase, excludePrefix, cellJson);
else
return convertSheetToDict(sheet, lowcase, excludePrefix, cellJson);
}
private object convertSheetToArray(DataTable sheet, bool lowcase, string excludePrefix, bool cellJson)
{
List