C#實(shí)現(xiàn)表格數(shù)據(jù)轉(zhuǎn)實(shí)體的示例代碼
場(chǎng)景
在實(shí)際開發(fā)過(guò)程中,特別是接口對(duì)接之類的,對(duì)于這種需求是屢見不鮮,現(xiàn)在很多在線平臺(tái)也都提供了像json轉(zhuǎn)實(shí)體、sql轉(zhuǎn)實(shí)體等。但是很多情況下,我們接收到的其實(shí)都是一份接口文檔,在文檔中利用表格標(biāo)明了字段的名稱、備注、類型等,而關(guān)于json什么的都是后來(lái)才有的,或者說(shuō),傳輸根本不用json。因此,表格數(shù)據(jù)能夠轉(zhuǎn)成實(shí)體類的需求就比較明顯了。
需求
所以,綜上場(chǎng)景所述,我們需要一個(gè)小工具,可以將表格數(shù)據(jù)直接轉(zhuǎn)換為c#代碼,當(dāng)然,本著通用化的思想,小工具當(dāng)然不會(huì)單純的做一個(gè)讀取excel文件的功能,這樣一點(diǎn)也不好用,因?yàn)橛善渌胤教峁┑奈臋n有的是excel,有的是word,所以,我們利用剪切板來(lái)做,只要解析剪切板的數(shù)據(jù)就可以了。
開發(fā)環(huán)境
.NET Framework版本:4.5
開發(fā)工具
Visual Studio 2013
實(shí)現(xiàn)代碼
public class GeneratorFieldModel { public string FieldDesc { get; set; } public string Modifier { get { return "public"; } } public string Type { get; set; } public string FieldName { get; set; } public string Property { get { return "{ get; set; }"; } } public bool IsNull { get; set; } public bool IsKey { get; set; } public string DefaultText { get; set; } readonly string startDesc = "\t\t/// <summary>"; readonly string endDesc = "\t\t/// </summary>"; public string FieldDescText { get { List<string> list = new List<string>(); list.Add(startDesc); list.Add("\t\t///" + FieldDesc + ""); list.Add(endDesc); return "\r\n" + string.Join("\r\n", list); } } public string PropertyText { get { return "\t\t" + string.Join(" ", Modifier, Type + (IsNull ? "?" : ""), FieldName, Property); } } }
public partial class Form_ToEntity : Form { BindingList<Entity> bindData = new BindingList<Entity>(); public Form_ToEntity() { InitializeComponent(); } private void Form_ToEntity_Load(object sender, EventArgs e) { string[] types = new string[]{ "string", "decimal", "double", "int", "bool", "long" }; DataGridViewComboBoxColumn dgvComboBox = Column2 as DataGridViewComboBoxColumn; dgvComboBox.Items.AddRange(types); dataGridView1.DataSource = bindData; } #region 處理點(diǎn)擊選中著色 private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { DataGridViewColumn selectColumn = dataGridView1.Columns[e.ColumnIndex]; Color color = selectColumn.DefaultCellStyle.BackColor == Color.LightGray ? Color.White : Color.LightGray; selectColumn.DefaultCellStyle.BackColor = color; selectColumn.HeaderCell.Style.BackColor = color; selectColumn.Tag = color; } private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex == -1 && e.ColumnIndex > -1) { DataGridViewColumn selectColumn = dataGridView1.Columns[e.ColumnIndex]; Color color = selectColumn.Tag == null ? Color.White : (Color)selectColumn.Tag; e.CellStyle.BackColor = color; } } #endregion /// <summary> /// 獲取剪切板數(shù)據(jù) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dataGridView1_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.V) { try { string text = Clipboard.GetText(); if (string.IsNullOrWhiteSpace(text)) { return; } string[] clipData = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries); bindData = Clip2Entity(clipData); dataGridView1.DataSource = new BindingList<Entity>(bindData); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } /// <summary> /// 將剪切板數(shù)據(jù)轉(zhuǎn)換為表格數(shù)據(jù) /// </summary> /// <param name="data"></param> /// <returns></returns> private BindingList<Entity> Clip2Entity(string[] data) { BindingList<Entity> list = new BindingList<Entity>(); foreach (string s in data) { Entity entity = new Entity(); string[] arr = s.Split('\t'); if (arr.Length == 2) { //選中名稱和類型 if (isCheck(dataGridView1.Columns[0]) && isCheck(dataGridView1.Columns[1])) { entity.name = arr[0]; entity.type = arr[1].ToLower(); entity.remark = ""; } //選中名稱和備注 if (isCheck(dataGridView1.Columns[0]) && isCheck(dataGridView1.Columns[2])) { entity.name = arr[0]; entity.type = "string"; entity.remark = arr[1]; } //選中類型和備注 if (isCheck(dataGridView1.Columns[1]) && isCheck(dataGridView1.Columns[2])) { entity.name = ""; entity.type = arr[0].ToLower(); entity.remark = arr[1]; } } else if (arr.Length == 3) { entity.name = arr[0]; entity.type = arr[1].ToLower(); entity.remark = arr[2]; } else { if (isCheck(dataGridView1.Columns[0])) { entity.name = s; entity.type = "string"; entity.remark = ""; } else if (isCheck(dataGridView1.Columns[1])) { entity.name = ""; entity.type = s.ToLower(); entity.remark = ""; } else if (isCheck(dataGridView1.Columns[2])) { entity.name = ""; entity.type = "string"; entity.remark = s; } } list.Add(entity); } return list; } /// <summary> /// 判斷列是否被選中 /// </summary> /// <param name="column"></param> /// <returns></returns> private bool isCheck(DataGridViewColumn column) { if (column.DefaultCellStyle.BackColor == Color.LightGray) { return true; } else { return false; } } private class Entity { public string name { get; set; } public string type { get; set; } public string remark { get; set; } } private void btn_add_Click(object sender, EventArgs e) { bindData.Add(new Entity { type = "string" }); } private void btn_delete_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.SelectedRows) { dataGridView1.Rows.Remove(row); } } private void btn_generate_Click(object sender, EventArgs e) { StringBuilder stringBuilder = new StringBuilder(); foreach (Entity entity in bindData) { GeneratorFieldModel field = new GeneratorFieldModel { FieldName = entity.name, FieldDesc = entity.remark, Type = entity.type }; stringBuilder.AppendLine(field.FieldDescText); stringBuilder.AppendLine(field.PropertyText); } string path = Application.StartupPath + "\\entity.txt"; File.WriteAllText(path, stringBuilder.ToString()); Process.Start(path); } }
實(shí)現(xiàn)效果
代碼解析:首先我們定義了一個(gè)GeneratorFieldModel
類,在這個(gè)類中根據(jù)不同的字段屬性進(jìn)行了代碼的拼接,這樣就可以很方便的調(diào)用,直接把值傳進(jìn)去即可得到要生成的實(shí)體代碼,然后在Ui中,首先處理了一下選中變色(標(biāo)識(shí)我們要處理哪些數(shù)據(jù)列),然后就是分析剪切板數(shù)據(jù),轉(zhuǎn)化成需要的結(jié)構(gòu)化數(shù)據(jù)(表格復(fù)制到剪切板的數(shù)據(jù),其實(shí)就是以"\r\n"
來(lái)分割的),顯示到dataGridView中。
到此這篇關(guān)于C#實(shí)現(xiàn)表格數(shù)據(jù)轉(zhuǎn)實(shí)體的示例代碼的文章就介紹到這了,更多相關(guān)C#表格數(shù)據(jù)轉(zhuǎn)實(shí)體內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# WinForm創(chuàng)建Excel文件的實(shí)例
下面小編就為大家?guī)?lái)一篇C# WinForm創(chuàng)建Excel文件的實(shí)例。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01C#?WPF實(shí)現(xiàn)播放音頻文件的示例詳解
這篇文章主要為大家詳細(xì)介紹了利用C#?WPF實(shí)現(xiàn)播放音頻文件的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03那些年,我還在學(xué)習(xí)C# 學(xué)習(xí)筆記
那些年學(xué)了ASP.NET后,才開始學(xué)習(xí)C#,說(shuō)來(lái)也怪,怎么學(xué)了ASP.NET才來(lái)學(xué)習(xí)C#,其實(shí)沒有什么的2012-03-03Unity 實(shí)現(xiàn)給物體替換材質(zhì)球
這篇文章主要介紹了Unity 實(shí)現(xiàn)給物體替換材質(zhì)球的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04C# winform 模擬鍵盤輸入自動(dòng)接入訪問(wèn)網(wǎng)絡(luò)的實(shí)例
本篇文章主要介紹了C# winform 模擬鍵盤輸入自動(dòng)接入訪問(wèn)網(wǎng)絡(luò),有興趣的可以了解一下。2016-11-11c#?Task.Wait()與awaiat?Task異常處理的區(qū)別說(shuō)明
這篇文章主要介紹了c#?Task.Wait()與awaiat?Task異常處理的區(qū)別說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06C#中數(shù)組、ArrayList、List、Dictionary的用法與區(qū)別淺析(存取數(shù)據(jù))
在工作中經(jīng)常遇到C#數(shù)組、ArrayList、List、Dictionary存取數(shù)據(jù),但是該選擇哪種類型進(jìn)行存儲(chǔ)數(shù)據(jù)呢?很迷茫,今天小編抽空給大家整理下這方面的內(nèi)容,需要的朋友參考下吧2017-02-02C#使用SqlConnection連接到SQL Server的代碼示例
這篇文章主要介紹了C#使用SqlConnection連接到SQL Server的代碼示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03