开发目的:
同事比较喜欢使用js文件,所以写了个工具将配置表转成js文件
上代码:
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
namespace CSV2JS
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("拖入CSV文件...");
string path = Console.ReadLine();
string outPath = path.Substring(0, path.LastIndexOf('\\')) + @"\_data.js";
OpenCSV(path, outPath);//读写取csv
Console.WriteLine("按任意键结束...");
Console.ReadLine();
}
public static void OpenCSV(string filePath ,string outPath)
{
FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.UTF8);
//记录每次读取的一行记录
string strLine;
string[] keys = { };
List<List<string>> values = new List<List<string>>();
bool isFirst = false;
List<string> outLines = new List<string>();
//写入信息
outLines.Add("var _data = {");
//逐行读取CSV中的数据
while ((strLine = sr.ReadLine()) != null)
{
if (isFirst == false)
{
isFirst = true;
keys = strLine.Split(",");
}
else
{
//{ id_1 : {key1:value1}, }
string[] value = strLine.Split(",");
string writeStr = "";
writeStr += ("\"" + keys[0] + "_" + value[0] + "\":{" );
for (int i = 1; i < value.Length; ++i)
{
writeStr += "\"" + keys[i] + "\":" + "\"" + value[i] + "\",";
}
writeStr = writeStr.Substring(0, writeStr.Length - 1);
writeStr += @"},";
outLines.Add(writeStr);
}
}
sr.Close();
fs.Close();
outLines.Add("}");
System.IO.File.WriteAllLines(outPath, outLines);
Console.WriteLine("输出路径:" + outPath);
}
}
}
运行效果:
创建个csv文件:
运行工程,拖入csv,回车:
导出的js文件:
规则如下:
1.第一行为表头,解释为主key值
2.导出的是一个字典
key1:是表头字段+数据值 "id_1"
key2:照搬表头