public void ExportToXls(object source, Fields fields, string fileName, Comfy.UI.WebControls.WebGridView.WebGridView gridView) { ICollection data = null; if (source is DataSet) { data = (source as DataSet).Tables[0].Rows; } else if (source is DataTable) { data = (source as DataTable).Rows; } else if (source is ICollection) { data = source as ICollection; } else { throw new NotSupportedException("source type:" + source.GetType()); } MemoryStream ms = new MemoryStream(); WriteToXls(data, fields, ms, gridView); //HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", fileName)); HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.End(); }
public void WriteToXls(ICollection source, Fields fields, MemoryStream ms, Comfy.UI.WebControls.WebGridView.WebGridView gridView) { Dictionary <string, int> formatStyles = new Dictionary <string, int>(); List <int> width = new List <int>(); ExportXlsProvider xls = new ExportXlsProvider(ms); xls.SetRange(fields.Count, source.Count + 1, true); int cellStyleIndex = xls.RegisterStyle(GetCellStyle()); int headerStyleIndex = xls.RegisterStyle(GetHeaderStyle()); CreateHeaderCells(xls, fields, width, headerStyleIndex); int rowIndex = 1; foreach (object obj in source) { CreateCells(xls, fields, width, cellStyleIndex, rowIndex, obj, gridView); rowIndex++; } xls.Commit(); }
public void ExportToXls(object source, Fields fields, Comfy.UI.WebControls.WebGridView.WebGridView gridView) { ExportToXls(source, fields, "data_" + System.DateTime.Now.ToString("yyyyMMddHHmmss"), gridView); }
private void CreateCells(ExportXlsProvider xls, Fields fields, List <int> width, int styleIndex, int rowIndex, object obj, Comfy.UI.WebControls.WebGridView.WebGridView gridView) { int colIndex = 0; Dictionary <string, int> formatStyles = new Dictionary <string, int>(); foreach (Field field in fields) { string value = null; if (obj is DataRow) { value = (obj as DataRow)[field.FieldName].ToString(); } else { value = obj.GetType().GetProperty(field.FieldName).GetValue(obj, null) == null ? string.Empty : obj.GetType().GetProperty(field.FieldName).GetValue(obj, null).ToString(); } value = gridView.GetLabelText(field, value); xls.SetCellData(colIndex, rowIndex, value); xls.SetCellStyle(colIndex, rowIndex, styleIndex); int w = GetFontWidth(value, xls.GetStyle(styleIndex).TextFont); if (w > width[colIndex]) { xls.SetColumnWidth(colIndex, w); } colIndex++; } }