发布网友 发布时间:2022-04-28 17:35
共2个回答
懂视网 时间:2022-05-03 11:56
C#" AutoEventWireup="true" CodeFile="导出到Excel.aspx.cs" Inherits="导出到Excel" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> </div> </form> </body> </html>后台代码
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using NPOI; using NPOI.SS.UserModel; using System.IO; public partial class 导出到Excel : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { DataTable dt =//利用你的orm框架得到数据源DataTable if (dt.Rows.Count > 0) { //创建工作簿 NPOI.SS.UserModel.IWorkbook workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(); //创建表 ISheet sheet = workbook.CreateSheet("vinkong");//表名 IRow row0 = sheet.CreateRow(0); row0.CreateCell(0).SetCellValue("id信息"); row0.CreateCell(1).SetCellValue("名称信息"); row0.CreateCell(2).SetCellValue("备注信息"); for (int r = 0; r < dt.Rows.Count; r++) { //创建行接受DataTable的行数据 IRow row = sheet.CreateRow(r + 1); row.CreateCell(0).SetCellValue(dt.Rows[r]["ID"].ToString()); row.CreateCell(1).SetCellValue(dt.Rows[r]["Code"].ToString()); row.CreateCell(2).SetCellValue(dt.Rows[r]["Name"].ToString()); } string filePath = Server.MapPath(@"./Files/vinkong" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");//存到项目Files文件夹下 //写文件 FileStream file = new FileStream(filePath, FileMode.Create); workbook.Write(file); file.Close(); //下载 FileInfo fileInfo = new FileInfo(filePath); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name); Response.AddHeader("Content-Length", fileInfo.Length.ToString()); Response.AddHeader("Content-Transfer-Encoding", "binary"); Response.ContentType = "application/octet-stream"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); Response.WriteFile(fileInfo.FullName); Response.Flush(); //删除文件 System.IO.File.Delete(filePath); Response.End(); } else { Response.Write("<script>alert(‘导出失败!‘)</script>"); } } }
WEB版利用NPOI导出数据库数据为Excel文件
标签:data 导出数据 linq eric add oct model str get
热心网友 时间:2022-05-03 09:04
word中WEB版式显示,意思是忽略你的页面设置中的纸张大小、页边距等,把所有内容显示在一起,就像一个WEB页面一样。