本文介绍了将数据导出到execl文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个gridview whick显示数据库中的数据。现在我想要在execl文件上导出
我该怎么办?
i have a gridview whick shows the data from the database.now i want that to be export on execl file
how will i do it??
推荐答案
protected void btnExport_Click(object sender, EventArgs e)
{
string strReport ="Report";
GetGridDetails(true); // Function to Bind GridView Data
ExportDataGrid(dgSRDetails, strReport);
}
public void ExportDataGrid(DataGrid oGrid, string exportFile)
{
//Clear the response, and set the content type and mark as attachment
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=\"" + exportFile + "\"");
Response.ContentType = "application/excel";
//Clear the character set
Response.Charset = "";
//Create a string and Html writer needed for output
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
//Clear the controls from the pased grid
ClearControls(oGrid);
//Show grid lines
oGrid.GridLines = GridLines.Both;
//Color header
oGrid.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
//Render the grid to the writer
oGrid.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
}
private void ClearControls(Control control)
{
//Recursively loop through the controls, calling this method
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
//If we have a control that is anything other than a table cell
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);
}
catch
{
}
control.Parent.Controls.Remove(control);
}
else if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
return;
}
var wb = new XLWorkbook();
var dataTable = GetTable("Information");
wb.Worksheets.Add(dataTable);
wb.SaveAs("AddingDataTableAsWorksheet.xlsx");
这篇关于将数据导出到execl文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!