将 gridview 导出到 Excel 电子表格的最佳方法是什么?这似乎很容易
除了我的 Gridview 没有导出属性。最快的方法是什么?
这可能有一些东西,但如果你想自己做,你可以编写一些代码来遍历 GridView.Rows 集合,然后在其中的 GridViewRow.Cells 集合。
从那里构建 CSV 文件应该很容易,Excel 可以毫无问题地读取它。
CSV 文件只是文本文件,其值包含在引号内,以逗号分隔。像这样:
"value", "value", "value"
"value", "value", "value"
您可以打开记事本并手动构建一个来尝试一下。
我已经这样做了好几次了。Excel 有一个 XML 版本。它以 .xml 扩展名结尾,但您只需将文件的扩展名更改为 .xls,XML 格式的文件就可以在 excel 中打开。
这种方法的最大障碍是 excel XML 格式。我通常以我想要的近似格式在 excel 中创建一个 excel 文件。然后我将 Excel 文件保存为 XML 格式,并在文本编辑器中打开它。
我通常从这个 Excel 示例页面创建一个模板文件。然后,当我在 Gridview 中导出信息时,我只需为包含我计划填充的单元格的部分创建 xml,我只需在模板文件中预先添加和附加文本。
打开 xml 格式的 excel 文件后,您将相对容易地找出所需的 XML。最难理解的部分是单元格引用格式选项的方式,这些选项位于 XML 文件的顶部。
祝你好运,如果您需要更多说明,请告诉我。
编辑: 您只需要创建一次模板 excel 文件,只是为了了解您需要生成的所需 xml。生成 xml 后,使用以下代码将其发送给用户:
string fileName = "ExportedFile.xls";
Response.Clear();
Response.Buffer = true;
Response.ContentType = "text/xml";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
ExportToExcel(HttpContext.Current.Response.OutputStream, testUID);
Response.End();
public static void ExportToExcel(Stream outputStream)
{
XmlTextWriter xmlSink = new XmlTextWriter(outputStream, Encoding.Default);
//ExcelHeaderString and ExcelStylesString are from the template
xmlSink.WriteRaw(ExcelHeaderString);
xmlSink.WriteRaw(ExcelStylesString);
//write your elements here
xmlSink.WriteElement("YourElements");
//ExcelFooterString is from the template
xmlSink.WriteRaw(ExcelFooterString);
}
在导出到 excel 中在 btnexporttoExcel 单击事件上编写此代码。
string attachment = "attachment; filename=Export.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
// Create a form to contain the grid
HtmlForm frm = new HtmlForm();
gv.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(gv);
frm.RenderControl(htw);
//GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
这个.net 库非常适合我们的用例。
该库允许您使用 XML 生成 Excel 工作簿,它 100% 使用 C# 构建,并且根本不需要安装 Excel 来生成文件。它公开了一个简单的对象模型来生成 XML 工作簿。
没有与 GridView 控件的内置集成,但编写通用适配器很容易,并且可以在其他项目中重用。
我用CarlosAg.ExcelXmlWriter
了链接。
我GridViews
HeaderCells
遍历所有行,然后遍历所有行。唯一的问题是,如果您允许分页并且您有多个页面,则必须将 PageSize 设置为一个较高的值(我设置为 10000000),然后DataBind
再次GridView
执行您的工作。然后将旧的 PageSize 值设置回来。如果有人知道更好的解决方案,不客气。
编辑: try/catch 在那里,因为由于某种原因,无法检查控件类型,然后强制转换为 Label 或LinkButton ==> control.GetType()
.
这是我的代码。
public static Workbook CreateWorkbook(GridView gridView)
{
int pageSize = gridView.PageSize;
gridView.PageSize = 10000000;
gridView.DataBind();
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets.Add("Export");
WorksheetStyle style = workbook.Styles.Add("headerStyle");
style.Font.Bold = true;
style = workbook.Styles.Add("defaultStyle");
style.Alignment.WrapText = true;
style = workbook.Styles.Add("infoStyle");
style.Font.Color = "Red";
style.Font.Bold = true;
sheet.Table.Rows.Add(new WorksheetRow());
WorksheetRow headerRow = new WorksheetRow();
foreach (DataControlFieldHeaderCell cell in gridView.HeaderRow.Cells)
{
if (!string.IsNullOrEmpty(cell.Text))
headerRow.Cells.Add(cell.Text, DataType.String, "headerStyle");
else
foreach (Control control in cell.Controls)
{
LinkButton linkButton = new LinkButton();
try
{
linkButton = (LinkButton)control;
}
catch { }
if (!string.IsNullOrEmpty(linkButton.Text))
headerRow.Cells.Add(linkButton.Text, DataType.String, "headerStyle");
else
{
Label label = new Label();
try
{
label = (Label)control;
}
catch { }
if (!string.IsNullOrEmpty(label.Text))
headerRow.Cells.Add(label.Text, DataType.String, "headerStyle");
}
}
}
sheet.Table.Rows.Add(headerRow);
foreach (GridViewRow row in gridView.Rows)
{
WorksheetRow wrow = new WorksheetRow();
foreach (TableCell cell in row.Cells)
{
foreach (Control control in cell.Controls)
{
if (control.GetType() == typeof(Label))
{
wrow.Cells.Add(((Label)control).Text, DataType.String, "defaultStyle");
}
}
}
sheet.Table.Rows.Add(wrow);
}
gridView.PageSize = pageSize;
return workbook;
}
此方法直接转换为 Excel 格式,无需在服务器上安装 XML 或使用 XML。
Protected Sub ExportToExcel()
Dim gv1 As GridView = FindControlRecursive(objPlaceHolder, "GridView1")
If Not gv1 Is Nothing Then
Response.ClearHeaders()
Response.ClearContent()
' Set the content type to Excel
Response.ContentType = "application/vnd.ms-excel"
' make it open the save as dialog
Response.AddHeader("content-disposition", "attachment; filename=ExcelExport.xls")
'Turn off the view state
Me.EnableViewState = False
'Remove the charset from the Content-Type header
Response.Charset = String.Empty
Dim myTextWriter As New System.IO.StringWriter
Dim myHtmlTextWriter As New System.Web.UI.HtmlTextWriter(myTextWriter)
Dim frm As HtmlForm = New HtmlForm()
Controls.Add(frm)
frm.Controls.Add(gv1)
'Get the HTML for the control
frm.RenderControl(myHtmlTextWriter)
'Write the HTML to the browser
Response.Write(myTextWriter.ToString())
'End the response
Response.End()
End If
End Sub
Private Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control
If root.ID = id Then
Return root
End If
Dim c As Control
For Each c In root.Controls
Dim t As Control = FindControlRecursive(c, id)
If Not t Is Nothing Then
Return t
End If
Next
Return Nothing
End Function
Private exportToExcel As Boolean = False
Private Sub LoadInExcel()
Me.Response.ClearContent()
Me.Response.AddHeader("content-disposition", "attachment; filename=MyFile.xls")
Me.Response.ContentType = "application/ms-excel"
Dim sw1 As New IO.StringWriter
Dim htw1 As HtmlTextWriter = New HtmlTextWriter(sw1)
GridView1.RenderControl(htw1)
Response.Write(sw1.ToString())
Response.End()
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Confirms that an HtmlForm control is rendered for the specified ASP.NET
' server control at run time.
End Sub
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
If exportToExcel Then
LoadInExcel()
End If
MyBase.Render(writer)
End Sub
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
exportToExcel = True
End Sub
您必须安装 excel 并在项目中引用 Office 互操作库。添加:
导入 Microsoft.Office.Core,导入 Microsoft.Office.Interop
上面的解决方案采用 gridview 并从中提取 html。然后将其写入excel。来自网格的 html 将包含样式属性,例如填充和颜色。它还将使可排序的列标题看起来像链接。当我使用它时,我编写了一个自定义解析器来去除所有不需要的样式,只给我原始数据。我将把这项任务留给你,因为它特定于每个网格。
包含对 VerifyRenderingInServerForm 的覆盖非常重要,即使其中没有任何代码。