• C# 如何将表格数据转成实体


    场景:在实际开发过程中,特别是接口对接之类的,对于这种需求是屡见不鲜,现在很多在线平台也都提供了像json转实体、sql转实体等。但是很多情况下,我们接收到的其实都是一份接口文档,在文档中利用表格标明了字段的名称、备注、类型等,而关于json什么的都是后来才有的,或者说,传输根本不用json。因此,表格数据能够转成实体类的需求就比较明显了。


    需求:所以,综上场景所述,我们需要一个小工具,可以将表格数据直接转换为c#代码,当然,本着通用化的思想,小工具当然不会单纯的做一个读取excel文件的功能,这样一点也不好用,因为由其他地方提供的文档有的是excel,有的是word,所以,我们利用剪切板来做,只要解析剪切板的数据就可以了。

    开发环境:.NET Framework版本:4.7.2

    开发工具: Visual Studio 2022

    实现代码:

    1. public class GeneratorFieldModel
    2. {
    3. public string FieldDesc { get; set; }
    4. public string Modifier { get { return "public"; } }
    5. public string Type { get; set; }
    6. public string FieldName { get; set; }
    7. public string Property { get { return "{ get; set; }"; } }
    8. public bool IsNull { get; set; }
    9. public bool IsKey { get; set; }
    10. public string DefaultText { get; set; }
    11. readonly string startDesc = "\t\t/// ";
    12. readonly string endDesc = "\t\t/// ";
    13. public string FieldDescText
    14. {
    15. get
    16. {
    17. List<string> list = new List<string>();
    18. list.Add(startDesc);
    19. list.Add("\t\t///" + FieldDesc + "");
    20. list.Add(endDesc);
    21. return "\r\n" + string.Join("\r\n", list);
    22. }
    23. }
    24. public string PropertyText
    25. {
    26. get { return "\t\t" + string.Join(" ", Modifier, Type + (IsNull ? "?" : ""), FieldName, Property); }
    27. }
    28. }
    1. public partial class Form_ToEntity : Form
    2. {
    3. BindingList<Entity> bindData = new BindingList<Entity>();
    4. public Form_ToEntity()
    5. {
    6. InitializeComponent();
    7. }
    8. private void Form_ToEntity_Load(object sender, EventArgs e)
    9. {
    10. string[] types = new string[]{
    11. "string",
    12. "decimal",
    13. "double",
    14. "int",
    15. "bool",
    16. "long"
    17. };
    18. DataGridViewComboBoxColumn dgvComboBox = Column2 as DataGridViewComboBoxColumn;
    19. dgvComboBox.Items.AddRange(types);
    20. dataGridView1.DataSource = bindData;
    21. }
    22. #region 处理点击选中着色
    23. private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    24. {
    25. DataGridViewColumn selectColumn = dataGridView1.Columns[e.ColumnIndex];
    26. Color color = selectColumn.DefaultCellStyle.BackColor == Color.LightGray ? Color.White : Color.LightGray;
    27. selectColumn.DefaultCellStyle.BackColor = color;
    28. selectColumn.HeaderCell.Style.BackColor = color;
    29. selectColumn.Tag = color;
    30. }
    31. private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    32. {
    33. if (e.RowIndex == -1 && e.ColumnIndex > -1)
    34. {
    35. DataGridViewColumn selectColumn = dataGridView1.Columns[e.ColumnIndex];
    36. Color color = selectColumn.Tag == null ? Color.White : (Color)selectColumn.Tag;
    37. e.CellStyle.BackColor = color;
    38. }
    39. }
    40. #endregion
    41. /// <summary>
    42. /// 获取剪切板数据
    43. /// </summary>
    44. /// <param name="sender"></param>
    45. /// <param name="e"></param>
    46. private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    47. {
    48. if (e.Control && e.KeyCode == Keys.V)
    49. {
    50. try
    51. {
    52. string text = Clipboard.GetText();
    53. if (string.IsNullOrWhiteSpace(text))
    54. {
    55. return;
    56. }
    57. string[] clipData = text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
    58. bindData = Clip2Entity(clipData);
    59. dataGridView1.DataSource = new BindingList<Entity>(bindData);
    60. }
    61. catch (Exception ex)
    62. {
    63. MessageBox.Show(ex.Message);
    64. }
    65. }
    66. }
    67. /// <summary>
    68. /// 将剪切板数据转换为表格数据
    69. /// </summary>
    70. /// <param name="data"></param>
    71. /// <returns></returns>
    72. private BindingList<Entity> Clip2Entity(string[] data)
    73. {
    74. BindingList<Entity> list = new BindingList<Entity>();
    75. foreach (string s in data)
    76. {
    77. Entity entity = new Entity();
    78. string[] arr = s.Split('\t');
    79. if (arr.Length == 2)
    80. {
    81. //选中名称和类型
    82. if (isCheck(dataGridView1.Columns[0]) && isCheck(dataGridView1.Columns[1]))
    83. {
    84. entity.name = arr[0];
    85. entity.type = arr[1].ToLower();
    86. entity.remark = "";
    87. }
    88. //选中名称和备注
    89. if (isCheck(dataGridView1.Columns[0]) && isCheck(dataGridView1.Columns[2]))
    90. {
    91. entity.name = arr[0];
    92. entity.type = "string";
    93. entity.remark = arr[1];
    94. }
    95. //选中类型和备注
    96. if (isCheck(dataGridView1.Columns[1]) && isCheck(dataGridView1.Columns[2]))
    97. {
    98. entity.name = "";
    99. entity.type = arr[0].ToLower();
    100. entity.remark = arr[1];
    101. }
    102. }
    103. else if (arr.Length == 3)
    104. {
    105. entity.name = arr[0];
    106. entity.type = arr[1].ToLower();
    107. entity.remark = arr[2];
    108. }
    109. else
    110. {
    111. if (isCheck(dataGridView1.Columns[0]))
    112. {
    113. entity.name = s;
    114. entity.type = "string";
    115. entity.remark = "";
    116. }
    117. else if (isCheck(dataGridView1.Columns[1]))
    118. {
    119. entity.name = "";
    120. entity.type = s.ToLower();
    121. entity.remark = "";
    122. }
    123. else if (isCheck(dataGridView1.Columns[2]))
    124. {
    125. entity.name = "";
    126. entity.type = "string";
    127. entity.remark = s;
    128. }
    129. }
    130. list.Add(entity);
    131. }
    132. return list;
    133. }
    134. /// <summary>
    135. /// 判断列是否被选中
    136. /// </summary>
    137. /// <param name="column"></param>
    138. /// <returns></returns>
    139. private bool isCheck(DataGridViewColumn column)
    140. {
    141. if (column.DefaultCellStyle.BackColor == Color.LightGray)
    142. {
    143. return true;
    144. }
    145. else
    146. {
    147. return false;
    148. }
    149. }
    150. private class Entity
    151. {
    152. public string name { get; set; }
    153. public string type { get; set; }
    154. public string remark { get; set; }
    155. }
    156. private void btn_add_Click(object sender, EventArgs e)
    157. {
    158. bindData.Add(new Entity
    159. {
    160. type = "string"
    161. });
    162. }
    163. private void btn_delete_Click(object sender, EventArgs e)
    164. {
    165. foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    166. {
    167. dataGridView1.Rows.Remove(row);
    168. }
    169. }
    170. private void btn_generate_Click(object sender, EventArgs e)
    171. {
    172. StringBuilder stringBuilder = new StringBuilder();
    173. foreach (Entity entity in bindData)
    174. {
    175. GeneratorFieldModel field = new GeneratorFieldModel
    176. {
    177. FieldName = entity.name,
    178. FieldDesc = entity.remark,
    179. Type = entity.type
    180. };
    181. stringBuilder.AppendLine(field.FieldDescText);
    182. stringBuilder.AppendLine(field.PropertyText);
    183. }
    184. string path = Application.StartupPath + "\\entity.txt";
    185. File.WriteAllText(path, stringBuilder.ToString());
    186. Process.Start(path);
    187. }
    188. }

    实现效果:

     代码解析:首先我们定义了一个GeneratorFieldModel类,在这个类中根据不同的字段属性进行了代码的拼接,这样就可以很方便的调用,直接把值传进去即可得到要生成的实体代码,然后在Ui中,首先处理了一下选中变色(标识我们要处理哪些数据列),然后就是分析剪切板数据,转化成需要的结构化数据(表格复制到剪切板的数据,其实就是以"\r\n"来分割的),显示到dataGridView中。

  • 相关阅读:
    Spring Boot 使用 .env 文件实现【隐私信息配置】
    网络部署思路、路由器以及静态路由协议
    编译原理总结
    Linux的tomcat的shutdown.sh关闭不了进程程
    玄机平台应急响应—apache日志分析
    路由框架 ARouter 原理及源码解析
    遇到了2个有相同的JavaBean类
    java ssm创意设计分享系统
    某黑产组织最新攻击样本利用BYVOD技术的详细分析
    基于排序变换混沌置乱算法的图像加密系统
  • 原文地址:https://blog.csdn.net/lwf3115841/article/details/127667197