2009-06-02 58 views
0

某些数据显示在datagridview(Winform)中。我有一个要求以类似的格式(行,列等)邮寄在datagridview中表示的表。我能做到的最简单的是什么?如何使用列标题将其转换为html表格并保留列宽。C#WinForm的DataGridView数据为html

+1

另请参阅:http://stackoverflow.com/questions/16008477/export-datagridview-to-html-page – 2016-09-10 01:50:35

回答

2

我不知道是否有任何框架级别的转换可以发生。但是,迭代栅格行和单元格,并使用宽度就绪的HTML重新创建它应该是一件非常简单的事情。

注销袖口,请原谅其不完整和任何简单的错误,但我认为你可以在这里得到基本的想法。

StringBuilder sb = new SringBuilder(); 

sb.AppendLine("<table>"); 
sb.AppendLine(" <tr>"); 
foreach(DataGridViewColumn column in grid.Columns) 
{ 
    sb.AppendLine(" <td>" + column.HeaderText + "</td>"); 
} 
sb.AppendLine(" </tr>");  

foreach(DataGridViewRow row in grid.Rows) 
{ 
    sb.AppendLine(" <tr>"); 
    foreach(DataGridViewCell cell in row.Cells) 
    { 
    sb.AppendLine(" <td width=\"" + cell.Width + "px\">" + cell.Value + "</td>"); 
    } 
    sb.AppendLine(" </tr>"); 
} 
sb.AppendLine("</table>"); 
1

我想,如果你搜索,你会发现这个网站

。如果你不这样做......

Do the following 
1. Create a stringbuilder, wrap it with htmlTextWriter 
2. Create a htmltable, add a header row, 
3. Iterate through the gridheaders and add cells, write the width in attributes, write other stuff like font, fontsize, forecolor, backcolor etc if you want 
4. Next iterate through the grid rows, add a row each time to table, add cells to row for each grid cells 
5. Call the render method passing the html writer 
6. Take the string builder out and you have a html table layout output.