本帖最后由 任文彬 于 2013-6-28 10:02 编辑
- public static class GridHelper
- {
- public static string FormatAsHtml(Grid grid, DataTable table)
- {
- var sb = new StringBuilder("<table frame='box' border='1'>");
- var fields=GetBoundFields(grid);
- AppendHeaderRow(fields, sb);
- AppendDataRow(fields, table, sb);
- sb.Append("</table>");
- return sb.ToString();
- }
- private static IList<BoundField> GetBoundFields(Grid grid)
- {
- var columns = new List<BoundField>();
- for (int i = 0; i < grid.Columns.Count; ++i)
- {
- var c = grid.Columns[i] as BoundField;
- if (c == null) //只导出BoundField
- continue;
- columns.Add(c);
- }
- return columns;
- }
- private static void AppendDataRow(IList<BoundField> fields, DataTable table, StringBuilder sb)
- {
- for (int rowIndex = 0; rowIndex < table.Rows.Count; ++rowIndex)
- {
- sb.Append("<tr>");
- for (int colIndex = 0; colIndex < fields.Count; ++colIndex)
- {
- AppendDataCell(sb, table.Rows[rowIndex], fields[colIndex].DataField, fields[colIndex].DataFormatString);
- }
- sb.Append("</tr>");
- }
- }
- private static void AppendDataCell(StringBuilder sb, DataRow row, string dataField, string dataFormat)
- {
- if (!row.Table.Columns.Contains(dataField))
- {
- sb.Append("<td></td>");
- }
- else
- {
- var data=row[dataField];
- if (data is Decimal || data is Double || data is Single)
- sb.Append("<td align='right'>");
- else
- sb.Append("<td>");
- string cellText = FormatCellText(dataFormat, data);
- sb.Append(cellText);
- sb.Append("</td>");
- }
- }
- private static string FormatCellText(string format, object data)
- {
- string cellText;
- if (data == null || Convert.IsDBNull(data))
- cellText = "";
- else if (string.IsNullOrEmpty(format))
- cellText = data.ToString();
- else
- cellText = string.Format(format, data);
- return cellText;
- }
- private static void AppendHeaderRow(IList<BoundField> fields, StringBuilder sb)
- {
- sb.Append("<tr style='font-weight:bold; text-align:center'>");
- for (int i = 0; i < fields.Count; ++i)
- {
- var col = fields[i];
- sb.Append("<td>").Append(col.HeaderText).Append("</td>");
- }
- sb.Append("</tr>");
- }
- }
复制代码 |