스토리지

CSV to JSON & CS prototype 1 본문

개발일지

CSV to JSON & CS prototype 1

ljw4104 2021. 5. 6. 11:39

외관

  1. csv 파일을 첨부한다
  2. 생성될 cs파일의 클래스 이름을 작성한다.
  3. Create
  4. csv 파일이 있는 폴더에서 cs파일을 확인

아직 json 연동은...

CSVToJsonCS.exe
0.01MB

 

코드

더보기
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace CsvToJsonCS
{
    public class GenerateCS
    {
        public static string CSharpClassCodeFromCsvFile(string filePath, string structureName,
            string delimiter = ",", string classAttribute = "", string propertyAttribute = "")
        {
            if (string.IsNullOrWhiteSpace(propertyAttribute) == false)
                propertyAttribute += "\n\t";
            if (string.IsNullOrWhiteSpace(propertyAttribute) == false)
                classAttribute += "\n";

            string[] lines = File.ReadAllLines(filePath);
            string[] columnNames = lines.First().Split(',').Select(str => str.Trim()).ToArray();
            string[] data = lines.Skip(1).ToArray();

            string className = structureName ?? Path.GetFileNameWithoutExtension(filePath);

            if (className.IndexOf('_') != -1)
            {
                className = className.Remove(className.IndexOf('_'));
            }
            if (className[0] >= 97)
            {
                var temp = className.ToCharArray();
                temp[0] -= (char)32;
                className = new string(temp);
            }
            string code = string.Format("{0}public class {1} {{ \n", classAttribute, className);

            for (int columnIndex = 0; columnIndex < columnNames.Length; columnIndex++)
            {
                var columnName = Regex.Replace(columnNames[columnIndex], @"[\s\.]", string.Empty, RegexOptions.IgnoreCase);
                if (string.IsNullOrEmpty(columnName))
                    columnName = "Column" + (columnIndex + 1);
                code += "\t" + GetVariableDeclaration(data, columnIndex, columnName, propertyAttribute) + "\n\n";
            }

            code += "}";
            return code;
        }

        public static string GetVariableDeclaration(string[] data, int columnIndex, string columnName, string attribute = null)
        {
            string[] columnValues = data.Select(line => line.Split(',')[columnIndex].Trim()).ToArray();
            string typeAsString;

            if (AllDateTimeValues(columnValues))
            {
                typeAsString = "DateTime";
            }
            else if (AllIntValues(columnValues))
            {
                typeAsString = "int";
            }
            else if (AllDoubleValues(columnValues))
            {
                typeAsString = "double";
            }
            else
            {
                typeAsString = "string";
            }

            string declaration = string.Format("{0}public {1} {2} {{ get; set; }}", attribute, typeAsString, columnName);
            return declaration;
        }

        public static bool AllDoubleValues(string[] values)
        {
            double d;
            return values.All(val => double.TryParse(val, out d));
        }

        public static bool AllIntValues(string[] values)
        {
            int d;
            return values.All(val => int.TryParse(val, out d));
        }

        public static bool AllDateTimeValues(string[] values)
        {
            DateTime d;
            return values.All(val => DateTime.TryParse(val, out d));
        }
    }
}

*참고

social.msdn.microsoft.com/Forums/vstudio/en-US/3790185d-32f2-4baa-ab11-dd18731bbb89/convert-csv-to-json-in-c?forum=winforms

 

Convert csv to json in C#

So I have the format for the json and I have the csv file loaded.. I just don't know how to convert the file... SaveFileDialog sfd = new SaveFileDialog(); OpenFileDialog ofd = new OpenFileDialog(); public static string fileName; private void open_btn_Click

social.msdn.microsoft.com

 

Comments