CSV(영어: comma-separated values)는 몇 가지 필드를 쉼표(,)로 구분한 텍스트 데이터 및 텍스트 파일이다. 확장자는 . csv이며 MIME 형식은 text/csv이다. comma-separated variables라고도 한다.
CSV - 나무위키
사실 CSV라는 포맷은 표준적으로 정의된 스키마(schema)나 데이터 타입이 있는 게 아니다. 구분자를 뭘로 쓰든 데이터를 주고받는 사이에 약속만 지키면 된다. 단지 주로 쓰는 구분자가 콤마일뿐. C
namu.wiki
[틀]
이름, 전화번호, 나이
A, 010, 25
B, 111, 45
엑셀파일 - CSV 파일로 뽑기
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//클래스 or 구조체로 만들기
[System.Serializable] //인스펙터창에 보이기 위함
public struct UserInfo
{
public string name;
public string phone;
public string email;
public int age;
public bool gender;
}
public class DataManager : MonoBehaviour
{
public List<UserInfo> allUser;
void Start()
{
allUser = CSV.instance.Parse("CSV_UNITY");
}
}
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class CSV : MonoBehaviour
{
public static CSV instance;
private void Awake()
{
if(instance == null)
{
instance = this;
}
}
public List<UserInfo> Parse(string fileName)
{
//전체 UserInfo를 가지고 있을 List
List<UserInfo> list = new List<UserInfo>();
//file을 읽어오자
string path = Application.streamingAssetsPath + "/" + fileName + ".csv";
string stringData = File.ReadAllText(path);
//print(stringData);
//엔터를 기준으로 한줄 한줄 자르자
//"\n" 으로 자르자
string[] lines = stringData.Split("\n"); //자른갯수만큼 배열로 반환
for(int i = 0; i < lines.Length; i++)
{
//남아있는 "\r"을 기준으로 나누자
string[] temp = lines[i].Split("\r");
lines[i] = temp[0];
}
// , 를 기준으로 변수를 나누자
string[] variables = lines[0].Split(",");
//, 를 기준으로 값을 나누자.
for(int i = 1; i < lines.Length; i++)
{
string[] values = lines[i].Split(",");
//잘라진 데이터를 가지고 UserInfo에 셋팅해서 리스트에 추가.
UserInfo info = new UserInfo();
info.name = values[0];
info.phone = values[1];
info.email = values[2];
info.age = int.Parse(values[3]);
info.gender = bool.Parse(values[4]);
list.Add(info);
}
return list;
}
}
리플렉션
참고: 리플렉션이란 객체를 통해 클래스의 정보를 분석해내는 프로그램 기법 Java에서는 Reflection 을 이용해 실행중인 자바 프로그램 내부의 클래스,필드,메서드의 속성을 조회,수정할 수 있습니다.
리플렉션을 사용하여 공통의 함수로 만들것임
-> 구조마다 따로 함수를 안만들어줘도 됨! 어떠한 csv 파일이든 읽을 수 있도록
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//클래스 or 구조체로 만들기
[System.Serializable] //인스펙터창에 보이기 위함
public class UserInfo
{
public string name;
public string phone;
public string email;
public int age;
public bool gender;
}
[System.Serializable]
public class ShopInfo
{
public string name;
public int price;
public int model;
}
public class DataManager : MonoBehaviour
{
public List<UserInfo> allUser;
public List<ShopInfo> allProduct;
void Start()
{
//allUser = CSV.instance.Parse("CSV_UNITY");
//allProduct = CSV.instance.Parse("CSV_SHOP");
allUser = CSV.instance.Parse<UserInfo>("CSV_UNITY");
allProduct = CSV.instance.Parse<ShopInfo>("CSV_SHOP");
}
void Update()
{
}
}
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using UnityEngine;
public class CSV : MonoBehaviour
{
public static CSV instance;
private void Awake()
{
if(instance == null)
{
instance = this;
}
}
public List<UserInfo> Parse(string fileName)
{
//전체 UserInfo를 가지고 있을 List
List<UserInfo> list = new List<UserInfo>();
//file을 읽어오자
string path = Application.streamingAssetsPath + "/" + fileName + ".csv";
string stringData = File.ReadAllText(path);
//print(stringData);
//엔터를 기준으로 한줄 한줄 자르자
//"\n" 으로 자르자
string[] lines = stringData.Split("\n"); //자른갯수만큼 배열로 반환
for(int i = 0; i < lines.Length; i++)
{
//남아있는 "\r"을 기준으로 나누자
string[] temp = lines[i].Split("\r");
lines[i] = temp[0];
}
// , 를 기준으로 변수를 나누자
string[] variables = lines[0].Split(",");
//, 를 기준으로 값을 나누자.
for(int i = 1; i < lines.Length; i++)
{
string[] values = lines[i].Split(",");
//잘라진 데이터를 가지고 UserInfo에 셋팅해서 리스트에 추가.
UserInfo info = new UserInfo();
info.name = values[0];
info.phone = values[1];
info.email = values[2];
info.age = int.Parse(values[3]);
info.gender = bool.Parse(values[4]);
list.Add(info);
}
return list;
}
public List<T> Parse<T>(string fileName) where T : new()
{
//전체 UserInfo를 가지고 있을 List
List<T> list = new List<T>();
//file을 읽어오자
string path = Application.streamingAssetsPath + "/" + fileName + ".csv";
string stringData = File.ReadAllText(path);
//print(stringData);
//엔터를 기준으로 한줄 한줄 자르자
//"\n" 으로 자르자
string[] lines = stringData.Split("\n"); //자른갯수만큼 배열로 반환
for (int i = 0; i < lines.Length; i++)
{
//남아있는 "\r"을 기준으로 나누자
string[] temp = lines[i].Split("\r");
lines[i] = temp[0];
}
// , 를 기준으로 변수를 나누자
string[] variables = lines[0].Split(",");
//, 를 기준으로 값을 나누자.
for (int i = 1; i < lines.Length; i++)
{
string[] values = lines[i].Split(",");
//※ 달라지는 부분
//잘라진 데이터를 가지고 UserInfo에 셋팅해서 리스트에 추가.
//제네릭으로 생성한 것을 T로 생성하고 싶으면 where T : new() 필요
T info = new T();
for(int j = 0; j < variables.Length; j++)
{
//T에 있는 변수들의 정보를 가져오자. typeof(T) 어떤 타입으로 되어있습니까
System.Reflection.FieldInfo fieldInfo = typeof(T).GetField(variables[j]); //변수이름대로 들어가 있음
//int.paser, byte.parse, bool.parse 것들을 fieldInfo를 이용해서 하자
TypeConverter typeConverter = TypeDescriptor.GetConverter(fieldInfo.FieldType);
//values 를 typeConverter 를 이용해서 변수에 셋팅
if(values[j].Length > 0)
{
fieldInfo.SetValue(info, typeConverter.ConvertFrom(values[j]));
}
}
list.Add(info);
}
return list;
}
}
TSV
728x90
'유니티' 카테고리의 다른 글
모바일 빌드 아이콘 넣기 (0) | 2023.11.28 |
---|---|
Json 직접파싱하기 (0) | 2023.11.17 |
Text Mesh Pro (0) | 2023.10.02 |
Button 상속 후 사용 (0) | 2023.09.30 |
Doxygen (0) | 2023.09.26 |