前台的代码(aspx)
<asp:Button ID="Button" runat="server" Text="导出exel表格" οnclick="Button_Click"/>
后台的代码(aspx.cs)
protected void Button_Click(object sender, EventArgs e)
{
string id = Convert.ToString(Session["sid"]);
string mima = Convert.ToString(Session["pasd"]);
Student student = new Student(id, mima);
DataTable refer_course = student.stu_look();
ExportExcel(refer_course);
}
protected void ExportExcel(DataTable dt)
{
HttpContext curContext = HttpContext.Current;
//设置编码及附件格式
curContext.Response.ContentType = "application/vnd.ms-excel";
curContext.Response.ContentEncoding = Encoding.UTF8;
curContext.Response.Charset = "";
string fullName = HttpUtility.UrlEncode("File.xls", Encoding.UTF8);
curContext.Response.AppendHeader("Content-Disposition",
"attachment;filename=" + HttpUtility.UrlEncode(fullName, Encoding.UTF8)); //attachment后面是分号
byte[] data = TableToExcel(dt, fullName).GetBuffer();
curContext.Response.BinaryWrite(TableToExcel(dt, fullName).GetBuffer());
curContext.Response.End();
}
public MemoryStream TableToExcel(DataTable dt, string file)
{
//创建workbook
IWorkbook workbook;
string fileExt = Path.GetExtension(file).ToLower();
if (fileExt == ".xlsx")
workbook = new XSSFWorkbook();
else if (fileExt == ".xls")
workbook = new HSSFWorkbook();
else
workbook = null;
//创建sheet
ISheet sheet = workbook.CreateSheet("Sheet1");
//表头
IRow headrow = sheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
ICell headcell = headrow.CreateCell(i);
headcell.SetCellValue(dt.Columns[i].ColumnName);
}
//表内数据
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
//转化为字节数组
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
return ms;
}
本文转载,飞本人所做,有被冒犯,请转告