asp.net生成Excel并导出下载五种实现方法

时间:2021-05-28

方法一通过GridView(简评:方法比较简单,但是只适合生成格式简单的Excel,且无法保留VBA代码),页面无刷新

aspx.cs部分
复制代码 代码如下:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text;

public partial class DataPage_NationDataShow : System.Web.UI.Page
{
private Data_Link link = new Data_Link();
private string sql;

protected void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(DataPage_NationDataShow));
}

protected void btnExcel_Click(object sender, EventArgs e)
{
string strExcelName = "MyExcel";
strExcelName = strExcelName.Replace(@"/", "");

Data_Link link = new Data_Link();
string strSQL = this.hidParam.Value;
DataSet ds = new DataSet();
ds = link.D_DataSet_Return(strSQL);//获得想要放入Excel的数据

gvExcel.Visible = true;
gvExcel.DataSource = null;
gvExcel.DataMember = ds.Tables[0].TableName;
gvExcel.DataSource = ds.Tables[0];
gvExcel.DataBind();

ExportToExcel(this.Page, gvExcel, strExcelName);
}

protected void gvExcel_RowDataBound(object sender, GridViewRowEventArgs e)
{ }
public override void VerifyRenderingInServerForm(Control control)
{ }

/// <summary>
/// 工具方法,Excel出力(解决乱码问题)
/// </summary>
/// <param name="page">调用页面</param>
/// <param name="excel">Excel数据</param>
/// <param name="fileName">文件名</param>
public void ExportToExcel(System.Web.UI.Page page, GridView excel, string fileName)
{
try
{
foreach (GridViewRow row in excel.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
excel.HeaderRow.Cells[i].BackColor = System.Drawing.Color.Yellow;
}
}
excel.Font.Size = 10;
excel.AlternatingRowStyle.BackColor = System.Drawing.Color.LightCyan;
excel.RowStyle.Height = 25;

page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
page.Response.Charset = "utf-8";
page.Response.ContentType = "application/vnd.ms-excel";
page.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
excel.Page.EnableViewState = false;
excel.Visible = true;
excel.HeaderStyle.Reset();
excel.AlternatingRowStyle.Reset();

System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
excel.RenderControl(oHtmlTextWriter);
page.Response.Write(oStringWriter.ToString());
page.Response.End();

excel.DataSource = null;
excel.Visible = false;
}
catch (Exception e)
{

}
}
}

aspx部分
复制代码 代码如下:
<head runat="server">
<script type="text/javascript">
//Excel DownLoad
function excelExport(){
var hidText = document.getElementById("hidParam");
hidText.value = "some params";
document.getElementById("ExcelOutput").click();
}
</script>
</head>
<body onload="pageInit()">
<form id="form1" runat="server">
<input type="button" value="EXCEL下载" style="width:100px;" onclick="excelExport()" id="excelBut" />
<input id="hidParam" type="text" runat="server" style="display:none;"/>
<asp:Button runat="server" ID="ExcelOutput" style="display:none" Text= "EXCEL出力" Width="0px" onclick="btnExcel_Click" UseSubmitBehavior="false"/>
<asp:GridView ID="gvExcel" runat="server" Height="95px" OnRowDataBound="gvExcel_RowDataBound" Visible="False"></asp:GridView>
</form>
</body>

在刚才的aspx.cs代码中
复制代码 代码如下:
foreach (GridViewRow row in excel.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
excel.HeaderRow.Cells[i].BackColor = System.Drawing.Color.Yellow;
}
}

这部分是给表头添加样式。

有时候为了便于浏览,需要给交叉行添加样式,简单点的可以用下面这种:
复制代码 代码如下:
excel.AlternatingRowStyle.BackColor = System.Drawing.Color.LightCyan;

但是细看一下会发现它把一整行的样式都改变了,包括后面那些没有用到的列。

解决办法是有,不过比较繁琐,就是修改每个单元格的样式。
复制代码 代码如下:
int rowCount = excel.Rows.Count;
int colCount = excel.HeaderRow.Cells.Count;

for (int i = 0; i < rowCount; i++)
{
for(int j=0;j<colCount; j++)
{
excel.Rows[i].Cells[j].BackColor = System.Drawing.Color.LightCyan;
}
}

方法二通过DataGrid(与方法一基本相同),页面无刷新

aspx.cs部分
复制代码 代码如下:
public override void VerifyRenderingInServerForm(Control control)
{}

/// <summary>
/// エクセル出力イベント
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ExcelBut_Click(object sender, System.EventArgs e)
{
DataGrid dgExcel = new DataGrid();

try
{
DataSet ds = getExcelData(this.PageParams.Value);//出力データを取得する

if(ds.Tables[0].Rows.Count>0)
{
//エクセルへデータを投入する
string execlName= "MyExcel";
Encoding encodingType=System.Text.Encoding.UTF8;
dgExcel.DataMember=ds.Tables[0].TableName;
dgExcel.DataSource=ds.Tables[0];

Response.Buffer = true;
Response.Charset = "utf-8";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + execlName+ ".xls");
Response.ContentEncoding = encodingType;
Response.ContentType = "application/ms-excel";
StringWriter oStringWriter = new StringWriter();
HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
dgExcel.DataBind();
dgExcel.Visible = true;
dgExcel.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.Flush();
Response.Close();
dgExcel.DataSource = null;
dgExcel.Visible = false;
}
else
{
Response.Write("<script>alert('xxxxxx')</script>");
}
}
catch(Exception ex)
{
Response.Write("<script>alert('oooooo')</script>");
}
}

aspx部分
复制代码 代码如下:
<head runat="server">
<script type="text/javascript">
//Excel DownLoad
function excelExport(){
var hidText = document.getElementById("hidParam");
hidText.value = "some params";
document.getElementById("ExcelOutput").click();
}
</script>
</head>
<body onload="pageInit()">
<form id="form1" runat="server">
<input type="button" value="EXCEL下载" style="width:100px;" onclick="excelExport()" id="excelBut" NAME="excelBut"/>
<input id="hidParam" type="text" runat="server" style="display:none;" NAME="hidParam"/>
<asp:Button runat="server" ID="ExcelOutput" style="display:none" Text= "EXCEL出力" Width="0px" onclick="btnExcel_Click" UseSubmitBehavior="false"/>
<asp:datagrid id="gvExcel" Visible="False" Runat="server" style="Z-INDEX: 107; POSITION: absolute; TOP: 72px; LEFT: 520px"
Width="80px" Height="40px"></asp:datagrid>
</form>
</body>

方法三以XML形式的Excel方式(可以设置丰富的样式,并可以有多个sheet,但需要模版。速度很快,但生成的文件较大,且无法保留VBA代码)

具体方法:把模版以 XML Document形式另存为A.xml。然后参照A.xml中的内容即可
复制代码 代码如下:
private void ExcelBut_Click(object sender, System.EventArgs e)
{
DataSet ds = new DataSet();
string ExcelFileName = "";
DataRow dr=[------列名信息-------];
try
{
ExcelFileName = Path.Combine(Request.PhysicalApplicationPath + "/ExcelFile", "MyExcel.xls");

//获取Excel需要的数据
ds = [------获得数据-------];
if (ds.Tables.Count == 0)
{
Response.Write("<script type='text/javascript'>alert('无数据');</script>");
return;
}
int sheetNum = ds.Tables.Count / 2;
StreamWriter writer = new StreamWriter(ExcelFileName, false);

//Styles标签前面的信息相当于'头信息',不需要改变
writer.WriteLine("<?xml version=\"1.0\"?>");
writer.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>");
writer.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
writer.WriteLine("xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
writer.WriteLine("xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
writer.WriteLine("xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
writer.WriteLine("xmlns:html=\"http://monTool
{
/// <summary>
/// 以流的形式,可以设置很丰富复杂的样式
/// </summary>
/// <param name="content">Excel中内容(Table格式)</param>
/// <param name="filename">文件名</param>
/// <param name="cssText">样式内容</param>
public static void ExportToExcel(string filename, string content,string cssText)
{
var res = HttpContext.Current.Response;
content = String.Format("<style type='text/css'>{0}</style>{1}",cssText,content);

res.Clear();
res.Buffer = true;
res.Charset = "UTF-8";
res.AddHeader("Content-Disposition", "attachment; filename=" + filename);
res.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
res.ContentType = "application/ms-excel;charset=UTF-8";
res.Write(content);
res.Flush();
res.End();
}
}

这种方法比较灵活,而且可以通过选择器来添加样式,相当不错。缺点就是需要将数据转换成字符串。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章