一个简单的问题,如何将这些内容转成数据表?

jacksoncan 2012-08-27 12:11:25
有一个richTextBox1控件,里面的string是如下内容:(格式跟显示的一样,有换行)

年份/项目
2011/12
2010/12
2009/12
2008/12
2007/12
盈利(百万)
130,446
102,311
45,249
44,398
149,276
盈利增长(%)
27.50
126.11
1.92
-70.26
21.64

现在的需要将这些string转成以下形式的数据表:

年份/项目 2011/12 2010/12 2009/12 ...
盈利(百万) 130,446 102,311 45,249 ...
...

就是以“年份/项目”作为列,其他对应作为数据构造一个数据表,显示在窗体的dataGridView1控件上,应该怎么做?恳请指教
...全文
62 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
jacksoncan 2012-08-27
  • 打赏
  • 举报
回复
非常感谢,不过我不想用那么多正则表达式,我已经想到怎么解决了,再次感谢您那么热心的帮助

[Quote=引用 1 楼 的回复:]

仅仅局限于本例
C# code
string text = @"年份/项目
2011/12
2010/12
2009/12
2008/12
2007/12
盈利(百万)
130,446
102,311
45,249
44,398
149,276
盈利增长(%)
27.50
126.11
1.92
-70.26
21.64";
DataTable dt = new D……
[/Quote]
  • 打赏
  • 举报
回复
仅仅局限于本例
string text = @"年份/项目
2011/12
2010/12
2009/12
2008/12
2007/12
盈利(百万)
130,446
102,311
45,249
44,398
149,276
盈利增长(%)
27.50
126.11
1.92
-70.26
21.64";
DataTable dt = new DataTable();
string pattern_column = @"(?<=^|\s+?)[\u4e00-\u9fa5()%/]+(?=\s+)";
foreach (Match m in Regex.Matches(text, pattern_column))
{
string column = m.Value;
dt.Columns.Add(new DataColumn(column,typeof(string)));
}
int rows = (Regex.Matches(text, @"\S+?(?=\s+|$)").Count - dt.Columns.Count) / dt.Columns.Count;
for (int i = 0; i < rows; i++)
{
DataRow dr = dt.NewRow();
foreach (DataColumn dc in dt.Columns)
{
string temp_name = Regex.Replace(dc.ColumnName,@"(?=[().])","\\");
string pattern_temp = @"(?<=" + temp_name + @"\s+?(\S+?\s+?){" + i + @"})\S+";
dr[dc.ColumnName] = Regex.Match(text,pattern_temp).Value;
}
dt.Rows.Add(dr);
}
this.dataGridView1.DataSource = dt;

110,568

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧