2009-06-02 36 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.