|
使用c#导出excel表格,需要用到npoi,介绍如下:
NPOI是指构建在POI 3.x版本之上的一个程序,NPOI可以在没有安装Office的情况下对Word或Excel文档进行读写操作。
NPOI是一个开源的C#读写Excel、WORD等微软OLE2组件文档的项目。
网上很多的代码,都需要把数据存到服务器,搞成物理文件,再导出(或者给一个下载链接),本帖子代码,不需要存物理文件,直接可以把list数据导出下载!
先看效果图:
我们用浏览器,访问:http://localhost:63096/api/download/test 接口地址,即可下载excel文件。
下载完成后,我们打开test.xls,可以正常打开和读取!如下图:
准备list数据,代码:
- public class UserInfo
- {
- public static List<UserInfo> GetList()
- {
- List<UserInfo> list = new List<UserInfo>();
- list.Add(new UserInfo("张山", "男", 18, "羽毛球"));
- list.Add(new UserInfo("李四", "男", 23, "篮球"));
- list.Add(new UserInfo("小渣渣", "男", 23, "编程"));
- list.Add(new UserInfo("小芳", "女", 25, "足球"));
- list.Add(new UserInfo("小花", "女", 11, "可乐"));
- list.Add(new UserInfo("架构师", "男", 4, "http://www.itsvse.com"));
- return list;
- }
- public UserInfo(string n,string s,int a,string l)
- {
- this.Name = n;
- this.Sex = s;
- this.Age = a;
- this.Like = l;
- }
- public string Name { get; set; }
- public string Sex { get; set; }
- public int Age { get; set; }
- public string Like { get; set; }
- }
复制代码
webapi代码如下:
- [HttpGet]
- public IHttpActionResult Test()
- {
- var browser = String.Empty;
- if (HttpContext.Current.Request.UserAgent != null)
- {
- browser = HttpContext.Current.Request.UserAgent.ToUpper();
- }
- HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
- #region 内容
- // Excel列的名称
- Dictionary<string, string> cellheader = new Dictionary<string, string> {
- { "Name", "姓名" },
- { "Sex", "性别" },
- { "Age", "年龄" },
- { "Like", "爱好" },
- };
- var info = EntityListToExcel2003(cellheader, UserInfo.GetList(), "用户信息");
- #endregion
- Stream stream = new MemoryStream(info);
- httpResponseMessage.Content = new StreamContent(stream);
- httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
- httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
- {
- FileName =
- browser.Contains("FIREFOX")
- ? Path.GetFileName("test.xlsx")
- : HttpUtility.UrlEncode(Path.GetFileName("test.xls"))
- };
- return ResponseMessage(httpResponseMessage);
- }
复制代码
EntityListToExcel2003方法如下:
|
上一篇: Asp.net mvc bundle将所有css文件打包在一起下一篇: vs2017 浏览器输入路径就终止调试
|