码迷,mamicode.com
首页 > Web开发 > 详细

csv(Excel)文件转Json

时间:2015-12-29 06:15:42      阅读:248      评论:0      收藏:0      [点我收藏+]

标签:

从一个心理学专业转到计算机,虽说两者八竿子打不着,但掐指一算正儿八经学编程已有两个多月,现在终于鼓起勇气写一写自己的博客。本篇写的是第一篇有关编程和unity的文章,希望自己在这道路上坚持走下去,也感谢身边的大神默默的支持。好了,废话不多说。  本篇是关于excel中csv格式的文件转换为json格式。。。

 

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using SimpleJSON;

public class ExcelToJson{

[MenuItem("ExcelToJson/AutoExcelJson")]
static void autoExcelToJson()
{
string excelFilePath=Application.dataPath+"/Data";
string outJsonDataPath=Application.dataPath+"/Json";

if(!Directory.Exists(excelFilePath))
{
Debug.Log("请创建"+excelFilePath+"文件夹,并把Csv文件放入此文件夹中");
return;
}

string[] allCsvFiles=Directory.GetFiles(excelFilePath,"*.csv");
if(allCsvFiles==null||allCsvFiles.Length<=0)
{
Debug.Log("请把Csv文件放入"+ excelFilePath+"此文件夹中");
return;
}

if(!Directory.Exists(outJsonDataPath))
{
Directory.CreateDirectory(outJsonDataPath);
}

for(int i=0;i<allCsvFiles.Length;i++)
{
string jsonData=excelDataToJsonData(allCsvFiles[i]);
string fileName=Path.GetFileNameWithoutExtension(allCsvFiles[i]);
saveJsonData(outJsonDataPath+"/"+fileName+".json",jsonData);
}
}

static string excelDataToJsonData(string excelFilePath)
{
if(!File.Exists(excelFilePath))
{
return null;
}

string fileContents=File.ReadAllText(excelFilePath,System.Text.Encoding.UTF8);
if(fileContents!=null)
{
string[] perRowContents=fileContents.Split(new string[]{"\r\n"},System.StringSplitOptions.None);
//获得注释的名字
string[] noteName=perRowContents[0].Split(new char[]{‘,‘},System.StringSplitOptions.None);
//获得变量的名字
string[] variableName=perRowContents[1].Split(new char[]{‘,‘},System.StringSplitOptions.None);
JSONClass jsonData=new JSONClass();
for(int i=2;i<perRowContents.Length-1;i++)
{
string[] rowContents=perRowContents[i].Split(new char[]{‘,‘},System.StringSplitOptions.None);
JSONClass rowClass=new JSONClass();
for(int j=1;j<rowContents.Length;j++)
{
rowClass[variableName[j]]=rowContents[j];
}
jsonData[rowContents[0]]=rowClass;
}
string resultJsonData=jsonData.ToString("");
return resultJsonData;
}

return null;
}

static void saveJsonData(string filePath,string jsonData)
{
if(filePath==null||jsonData==null)
{
return;
}

string directName=Path.GetDirectoryName(filePath);
Debug.Log("directName: "+directName);
if(!Directory.Exists(directName))
{
Directory.CreateDirectory(directName);
}

File.WriteAllText(filePath,jsonData,System.Text.Encoding.UTF8);
Debug.Log("json数据保存成功");
}

}

 

csv(Excel)文件转Json

标签:

原文地址:http://www.cnblogs.com/zhang20151228/p/5084506.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!