NPIO文件下载地址:http://npoi.codeplex.com/将文件直接引用至项目中即可,,,,,虽然网上资料很多,但有可能并找不到自己想要的功能,今天闲的没事,所以就稍微整理了一个简单的例子,希望自己在以后的项目中用得着,到时候就不用在网上查找了,直接把代码copy过 ...
NPIO文件下载地址:http://npoi.codeplex.com/
将文件直接引用至项目中即可,,,,,
虽然网上资料很多,但有可能并找不到自己想要的功能,今天闲的没事,所以就稍微整理了一个简单的例子,希望自己在以后的项目中用得着,到时候就不用在网上查找了,直接把代码copy过来就可以啦~~~~主要是在get='_blank'>mvc控制器里面敲的,直接贴代码了。。。。。
1、逻辑代码
public EmptyResult ExportExcle() { HSSFCellStyle style; HSSFFont font;#if DEBUG UserInfo u = new UserInfo(); List<UserInfo> list = u.GetDate(); string url = Server.MapPath(@"\Content\File\MyBook.xls"); string sheetName = "MySheet";#endif HSSFWorkbook hssfworkbook = new HSSFWorkbook(); FileStream filecreate = new FileStream(url, FileMode.Create, FileAccess.ReadWrite); //创建工作表 HSSFSheet sheet = hssfworkbook.CreateSheet(sheetName) as HSSFSheet; IRow row = sheet.CreateRow(0); row.CreateCell(0).SetCellValue("用户编号"); row.CreateCell(1).SetCellValue("用户名"); row.CreateCell(2).SetCellValue("性别"); row.CreateCell(3).SetCellValue("年龄"); row.CreateCell(4).SetCellValue("电话"); row.CreateCell(5).SetCellValue("身份证"); //行高 row.HeightInPoints = 20; //给表头单元格设置样式(对齐方式、边框、字体、背景颜色) List<ICell> cell = row.Cells; style = hssfworkbook.CreateCellStyle() as HSSFCellStyle; font = hssfworkbook.CreateFont() as HSSFFont; font.IsBold = true;//加粗 font.FontName = "宋体"; font.Color = HSSFColor.Red.Index;//字体颜色 style.SetFont(font); this.CellStyle(style, sheet); style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Green.Index; style.FillPattern = FillPattern.SolidForeground; cell.ForEach(delegate(ICell c) { c.CellStyle = style; }); //加载内容 if (list.Any()) { style = hssfworkbook.CreateCellStyle() as HSSFCellStyle; this.CellStyle(style, sheet); for (int i = 0; i < list.Count; i++) { row = sheet.CreateRow(i + 1); row.HeightInPoints = 20; row.CreateCell(0).SetCellValue(list[i].UserId); row.CreateCell(1).SetCellValue(list[i].UserName); row.CreateCell(2).SetCellValue(list[i].Sex); row.CreateCell(3).SetCellValue(list[i].Age); row.CreateCell(4).SetCellValue(list[i].Tel); row.CreateCell(5).SetCellValue(list[i].IdCard); cell = row.Cells; cell.ForEach(p => p.CellStyle = style); } } //将流写入excel文件 hssfworkbook.Write(filecreate); filecreate.Close(); #region 下载文件 FileStream fileopen = new FileStream(url, FileMode.Open); byte[] bytes = new byte[(int)fileopen.Length]; fileopen.Read(bytes, 0, bytes.Length); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("MyBook.xls", System.Text.Encoding.UTF8)); Response.BinaryWrite(bytes); fileopen.Close(); Response.Flush(); Response.End(); return new EmptyResult(); #endregion }
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:NPOI生成excel并下载
关键词:excel
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。