using System;
using System.IO;
using System.Data;
using System.Text;
using System.Collections.Generic;
namespace excel2json
{
///
/// 根据表头,生成C#类定义数据结构
/// 表头使用三行定义:字段名称、字段类型、注释
///
class LuaDefineGenerator
{
struct FieldDef
{
public string name;
public string type;
public string comment;
}
string mCode;
public string code {
get {
return this.mCode;
}
}
public LuaDefineGenerator(string excelName, ExcelLoader excel, string excludePrefix)
{
//-- 创建代码字符串
StringBuilder sb = new StringBuilder();
sb.AppendLine("--[[");
sb.AppendLine("1. 每个 Sheet 形成一个 常量类 定义, Sheet 的名称作为 常量类 的名称");
sb.AppendLine("2. 表格约定:第一行是变量名称,第二行是变量类型");
sb.AppendLine();
sb.AppendFormat("Generate From {0}", excelName);
sb.AppendLine("\n]]--");
sb.AppendLine();
sb.AppendLine();
for (int i = 0; i < excel.Sheets.Count; i++)
{
DataTable sheet = excel.Sheets[i];
sb.Append(_exportSheet(sheet, excludePrefix));
}
sb.AppendLine();
mCode = sb.ToString();
}
private string _exportSheet(DataTable sheet, string excludePrefix)
{
if (sheet.Columns.Count < 0 || sheet.Rows.Count < 2)
return "";
string sheetName = sheet.TableName;
if (excludePrefix.Length > 0 && sheetName.StartsWith(excludePrefix))
return "";
// get field list
List fieldList = new List();
DataRow typeRow = sheet.Rows[0];
DataRow commentRow = sheet.Rows[1];
int firstDataRow = 2;
for (int i = firstDataRow; i < sheet.Rows.Count; i++)
{
DataRow row = sheet.Rows[i];
string key = row[sheet.Columns[0]].ToString();
if (excludePrefix.Length > 0 && key.StartsWith(excludePrefix))
continue;
FieldDef field;
field.name = key.ToString();
field.type = "";
field.comment = key.ToString();
fieldList.Add(field);
}
// export as string
StringBuilder sb = new StringBuilder();
sb.AppendFormat("local {0}Key =\r\n{{", sheet.TableName);
sb.AppendLine();
foreach (FieldDef field in fieldList)
{
sb.AppendFormat("\t{0} = \"{1}\", ",field.name, field.comment);
sb.AppendLine();
}
sb.Append('}');
sb.AppendFormat("\n\nreturn {0}Key", sheet.TableName);
sb.AppendLine();
sb.AppendLine();
return sb.ToString();
}
public void SaveToFile(string filePath, Encoding encoding)
{
//-- 保存文件
using (FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
using (TextWriter writer = new StreamWriter(file, encoding))
writer.Write(mCode);
}
}
}
}