C#實(shí)現(xiàn)表格數(shù)據(jù)轉(zhuǎn)實(shí)體的示例代碼
場(chǎng)景
在實(shí)際開(kāi)發(fā)過(guò)程中,特別是接口對(duì)接之類的,對(duì)于這種需求是屢見(jiàn)不鮮,現(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ù)就可以了。
開(kāi)發(fā)環(huán)境
.NET Framework版本:4.5
開(kāi)發(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#實(shí)現(xiàn)將日志寫(xiě)入文本文件的方法
這篇文章主要介紹了C#實(shí)現(xiàn)將日志寫(xiě)入文本文件的方法,涉及C#針對(duì)日志文件寫(xiě)入的相關(guān)技巧,需要的朋友可以參考下2015-05-05
C#編程實(shí)現(xiàn)連接SQL SERVER數(shù)據(jù)庫(kù)實(shí)例詳解
這篇文章主要介紹了C#編程實(shí)現(xiàn)連接SQL SERVER數(shù)據(jù)庫(kù)的方法,以實(shí)例形式較為詳細(xì)的分析了C#連接SQL SERVER數(shù)據(jù)庫(kù)的相關(guān)步驟與具體實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-11-11
C#連接Oracle數(shù)據(jù)庫(kù)的多種方法總結(jié)
最近小項(xiàng)目當(dāng)中要使用C#來(lái)連接Oracle數(shù)據(jù)庫(kù)來(lái)完成系統(tǒng)的操作,這篇文章主要給大家介紹了關(guān)于C#連接Oracle數(shù)據(jù)庫(kù)的多種方法,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04
講解C#面相對(duì)象編程中的類與對(duì)象的特性與概念
這篇文章主要介紹了C#面相對(duì)象編程中的類與對(duì)象的特性與概念,OOP面向?qū)ο笳Z(yǔ)言相對(duì)C語(yǔ)言這樣面相過(guò)程的語(yǔ)言來(lái)說(shuō)具有類和對(duì)象以及方法這樣的特性,需要的朋友可以參考下2016-01-01

