文字範本(T4) - CsvImport

簡單練習一下
1.在.tt 內,給定 csv 檔案路徑
2.執行 .tt 內產生的 method 來取得資料
 

                                 ↓有些 csv 需要手動修正一下
練習的 csv 檔為:https://github.com/tmcnab/northwind-mongo


.tt 的內容為

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>
<#
	string filePath = @"C:\csharp\northwind\employees.csv";
	string className = filePath.Substring(
		filePath.LastIndexOf('\\')+1,
		filePath.LastIndexOf('.')-filePath.LastIndexOf('\\')-1
	);
	int lineCount = 0;
	int colCount = 0;
	string properties = "";
	string consturctorParameters = "";
	string constructorContent = "";
	string constructorValues = "";
	string toString = "";

	using (var sr = new StreamReader(filePath))
	{
		string str = sr.ReadLine();
		string[] columns = str.Split(',');
		colCount = columns.Length;
		constructorValues = string.Join(",",Enumerable.Range(0,colCount).Select(s => "dataArray["+s+"]"));
		List<string> propertiesList = new List<string>();
		List<string> consturctorParametersList = new List<string>();
		List<string> constructorContentList = new List<string>();
		List<string> toStringList = new List<string>();
		foreach (var col in columns)
		{
			propertiesList.Add("public string " + col + "{ get; set; }");
			consturctorParametersList.Add("string s"+col);
			constructorContentList.Add(col+" = s"+col+";");
			toStringList.Add("\""+col+":\"+" + col);
		}

		properties = string.Join("\r\n", propertiesList);
		consturctorParameters = string.Join(",", consturctorParametersList);
		constructorContent = string.Join("\r\n", constructorContentList);
		toString = string.Join("+\"\\t\"+", toStringList);

		while (!sr.EndOfStream)
		{
			sr.ReadLine();
			lineCount++;
		}
	}
#>
using System.Collections.Generic;
using System.IO;
namespace csvImport
{
	public partial class CsvClass
	{
		private int _lineCount = <#=lineCount#> ;
		private string _filePath = @"<#=filePath#>";
		
		public List<<#=className#>> getData()
		{
            List<<#=className#>> result = new List<<#=className#>>();
            int lineCount = 0;
            using (var sr = new StreamReader(_filePath))
            {
                string str = sr.ReadLine();
                while (!sr.EndOfStream)
                {
                    str = sr.ReadLine();
                    string[] dataArray = str.Split(',');
                    result.Add(new <#=className#>(<#=constructorValues#>));
                    lineCount++;
                }
            }
            return result;
		}

		public partial class <#=className#>
		{
<#=properties#>

			public <#=className#>(<#=consturctorParameters#>)
			{
<#=constructorContent#>
			}

			public string toString()
            {
				return <#=toString#>;
            }
		}
	}
}


產生的 .cs 內容為

using System.Collections.Generic;
using System.IO;
namespace csvImport
{
	public partial class CsvClass
	{
		private int _lineCount = 12 ;
		private string _filePath = @"C:\csharp\northwind\employees.csv";
		
		public List<employees> getData()
		{
            List<employees> result = new List<employees>();
            int lineCount = 0;
            using (var sr = new StreamReader(_filePath))
            {
                string str = sr.ReadLine();
                while (!sr.EndOfStream)
                {
                    str = sr.ReadLine();
                    string[] dataArray = str.Split(',');
                    result.Add(new employees(dataArray[0],dataArray[1],dataArray[2],dataArray[3],dataArray[4],dataArray[5],dataArray[6],dataArray[7],dataArray[8],dataArray[9],dataArray[10],dataArray[11],dataArray[12],dataArray[13],dataArray[14],dataArray[15],dataArray[16],dataArray[17]));
                    lineCount++;
                }
            }
            return result;
		}

		public partial class employees
		{
public string EmployeeID{ get; set; }
public string LastName{ get; set; }
public string FirstName{ get; set; }
public string Title{ get; set; }
public string TitleOfCourtesy{ get; set; }
public string BirthDate{ get; set; }
public string HireDate{ get; set; }
public string Address{ get; set; }
public string City{ get; set; }
public string Region{ get; set; }
public string PostalCode{ get; set; }
public string Country{ get; set; }
public string HomePhone{ get; set; }
public string Extension{ get; set; }
public string Photo{ get; set; }
public string Notes{ get; set; }
public string ReportsTo{ get; set; }
public string PhotoPath{ get; set; }

			public employees(string sEmployeeID,string sLastName,string sFirstName,string sTitle,string sTitleOfCourtesy,string sBirthDate,string sHireDate,string sAddress,string sCity,string sRegion,string sPostalCode,string sCountry,string sHomePhone,string sExtension,string sPhoto,string sNotes,string sReportsTo,string sPhotoPath)
			{
EmployeeID = sEmployeeID;
LastName = sLastName;
FirstName = sFirstName;
Title = sTitle;
TitleOfCourtesy = sTitleOfCourtesy;
BirthDate = sBirthDate;
HireDate = sHireDate;
Address = sAddress;
City = sCity;
Region = sRegion;
PostalCode = sPostalCode;
Country = sCountry;
HomePhone = sHomePhone;
Extension = sExtension;
Photo = sPhoto;
Notes = sNotes;
ReportsTo = sReportsTo;
PhotoPath = sPhotoPath;
			}

			public string toString()
            {
				return "EmployeeID:"+EmployeeID+"\t"+"LastName:"+LastName+"\t"+"FirstName:"+FirstName+"\t"+"Title:"+Title+"\t"+"TitleOfCourtesy:"+TitleOfCourtesy+"\t"+"BirthDate:"+BirthDate+"\t"+"HireDate:"+HireDate+"\t"+"Address:"+Address+"\t"+"City:"+City+"\t"+"Region:"+Region+"\t"+"PostalCode:"+PostalCode+"\t"+"Country:"+Country+"\t"+"HomePhone:"+HomePhone+"\t"+"Extension:"+Extension+"\t"+"Photo:"+Photo+"\t"+"Notes:"+Notes+"\t"+"ReportsTo:"+ReportsTo+"\t"+"PhotoPath:"+PhotoPath;
            }
		}
	}
}


執行的程式

using System;

namespace csvImport
{
    class Program
    {
        static void Main(string[] args)
        {
            CsvClass cc = new CsvClass();
            var result = cc.getData();
            result.ForEach(r =>
            {
                Console.WriteLine(r.toString());
            });
            Console.ReadLine();
        }
    }
}