NPOI导出Excel并下载到客户端

news/2024/7/21 7:32:25 标签: excel

报表数据导出Excel,很常见的需求,然而每次都能忘了,今天再次遇到了,总结一下。


一般来说都需要有个标题

//需要输出的字段
string[] fieldArr = { "Title", "Sequence", "WorkSheetDescription", "Position", "StartTime", "EndTime", "Transactor", "Status", "WorkClass", "Result", "StartDoTime", "EndDoTime" };

//对应的中文描述            System.Collections.Generic.Dictionary<string, string> fieldDic = new System.Collections.Generic.Dictionary<string, string> { { "Title", "工单编号" }, { "Sequence", "顺序" }, { "WorkSheetDescription", "工单描述" }, { "Position", "位置" }, { "StartTime", "计划开始时间" }, { "EndTime", "计划结束时间" }, { "Transactor", "处理人" }, { "Status", "工单状态" }, { "WorkClass", "班次" }, { "Result", "执行结果" }, { "StartDoTime", "实际开始时间" }, { "EndDoTime", "实际结束时间" } };

设置表单表格样式

ICellStyle titleStyle= wb.CreateCellStyle();
            IFont font1 = wb.CreateFont();//字体
            font1.FontName = "楷体";
            font1.Color = HSSFColor.White.Index;//字体颜色
            font1.Boldweight = (short)FontBoldWeight.Normal;//字体加粗
            titleStyle.SetFont(font1);//字体设置具体的字体
            //背景色
            titleStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Blue.Index;
            titleStyle.FillPattern = FillPattern.SolidForeground;
            titleStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Blue.Index;
            titleStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平对齐方式
            titleStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直对齐方式

设置列宽

int[] columnWidth = { 10, 10, 25, 10, 15, 15, 20, 10, 20, 20, 15, 15 };
            for (int i = 0; i < columnWidth.Length; i++)
            {
                //设置列宽度,256*字符数,因为单位是1/256个字符
                sheet.SetColumnWidth(i, 256 * columnWidth[i]);
            }

把生成的Excel发送到客户端

MemoryStream ms = new MemoryStream();
            wb.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode("WS" + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8)));
            Response.BinaryWrite(ms.ToArray());
            Response.Flush();

            Response.End();
            wb = null;
            ms.Close();
            ms.Dispose();

因为我的项目是SharePoint的,所以数据源是SPListItemCollection传入,其他的DataTable或者其他的相应改动一下就行。

代码如下

public void NPOIExcel(SPListItemCollection items)
        {
            HSSFWorkbook wb = new HSSFWorkbook();

            //标题样式样式
            ICellStyle titleStyle= wb.CreateCellStyle();
            IFont font1 = wb.CreateFont();//字体
            font1.FontName = "楷体";
            font1.Color = HSSFColor.White.Index;//字体颜色
            font1.Boldweight = (short)FontBoldWeight.Normal;//字体加粗
            titleStyle.SetFont(font1);//设置字体
            //设置背景色
            titleStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Blue.Index;
            titleStyle.FillPattern = FillPattern.SolidForeground;
            titleStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Blue.Index;
            titleStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平对齐方式
            titleStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直对齐方式

            //创建一个表单
            ISheet sheet = wb.CreateSheet("Sheet0");
            //设置列宽
            int[] columnWidth = { 10, 10, 25, 10, 15, 15, 20, 10, 20, 20, 15, 15 };
            for (int i = 0; i < columnWidth.Length; i++)
            {
                //设置列宽度,256*字符数,因为单位是1/256个字符
                sheet.SetColumnWidth(i, 256 * columnWidth[i]);
            }

            IRow row;
            ICell cell;

            string[] fieldArr = { "Title", "Sequence", "WorkSheetDescription", "Position", "StartTime", "EndTime", "Transactor", "Status", "WorkClass", "Result", "StartDoTime", "EndDoTime" };
            System.Collections.Generic.Dictionary<string, string> fieldDic = new System.Collections.Generic.Dictionary<string, string> { { "Title", "工单编号" }, { "Sequence", "顺序" }, { "WorkSheetDescription", "工单描述" }, { "Position", "位置" }, { "StartTime", "计划开始时间" }, { "EndTime", "计划结束时间" }, { "Transactor", "处理人" }, { "Status", "工单状态" }, { "WorkClass", "班次" }, { "Result", "执行结果" }, { "StartDoTime", "实际开始时间" }, { "EndDoTime", "实际结束时间" } };

            //写入标题行
            row = sheet.CreateRow(0);
            for (int i = 0; i < fieldArr.Length; i++)
            {
                cell = row.CreateCell(i);//创建第j列
                cell.CellStyle = titleStyle;
                SetCellValue(cell, fieldDic[fieldArr[i]]);
            }

            //写入数据,从第2行开始
            for (int i = 1; i <= items.Count; i++)
            {
                row = sheet.CreateRow(i);//创建第i行
                for (int j = 0; j < fieldArr.Length; j++)
                {
                    cell = row.CreateCell(j);

                    //根据数据类型设置不同类型的cell
                    var field = fieldArr[j];
                    object obj = null;
                    //如果报错,跳过该字段
                    try
                    {
                        obj = items[i - 1][field];
                    }
                    catch
                    {
                        continue;
                    }
                    if (obj != null)
                    {
                        SetCellValue(cell, obj);
                    }
                }
            }

            //发送到客户端
            MemoryStream ms = new MemoryStream();
            wb.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode("WS" + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8)));
            Response.BinaryWrite(ms.ToArray());
            Response.Flush();

            Response.End();
            wb = null;
            ms.Close();
            ms.Dispose();
        }

        /// <summary>
        /// 根据数据类型设置不同类型的cell
        /// </summary>
        /// <param name="cell"></param>
        /// <param name="obj"></param>
        public static void SetCellValue(ICell cell, object obj)
        {
            try
            {
                if (obj.GetType() == typeof(int))
                {
                    cell.SetCellValue((int)obj);
                }
                else if (obj.GetType() == typeof(double))
                {
                    cell.SetCellValue((double)obj);
                }
                else if (obj.GetType() == typeof(IRichTextString))
                {
                    cell.SetCellValue((IRichTextString)obj);
                }
                else if (obj.GetType() == typeof(string))
                {
                    cell.SetCellValue(obj.ToString());
                }
                else if (obj.GetType() == typeof(DateTime))
                {
                    cell.SetCellValue(Convert.ToDateTime(obj).ToString("yyyy/MM/dd"));
                }
                else if (obj.GetType() == typeof(bool))
                {
                    cell.SetCellValue((bool)obj);
                }
                else
                {
                    cell.SetCellValue(obj.ToString());
                }
            }
            catch (Exception ex)
            {
            }
        }

需要注意的是,如果在页面直接用按钮事件导出Excel的话,只能导出一次,然后因为页面被End了,导致页面没有刷新,如果需要多次导出的话,可以把下载的操作放到一个页面去执行,然后前端js创建iframe的方式去做。

好记忆不如烂笔头,记录一下,免得以后又要到处找。


http://www.niftyadmin.cn/n/1246143.html

相关文章

mysql 创建唯一索引_MySQL索引创建(优化规则)

mysql的数据索引我们开发的时候一定都会用到&#xff0c;比如我们的主键、唯一等这些都是有到索引的内容&#xff0c;但是如果只有这样的索引在我们的实际开发中肯定满足不了我们的需求&#xff0c;这个时候就需要我们来创建相关的索引&#xff0c;但是索引创建并不是胡乱的创建…

SharePoint 2013 多表查询的 0x80070057 错误

环境&#xff1a;SharePoint 2013 场景&#xff1a;在SharePoint 2013 下面进行多表查询。 做表报的时候要做多表查询&#xff0c;然后百度到SPQuery&#xff0c;然后照着写&#xff0c;一直报下面这个错误。。。 System.ArgumentException: 0x80070057 在 Microsoft.ShareP…

vtk鼠标不交互_Axure RP 9萌新修炼手册第五章交互应用(9)

五、更新实际上&#xff0c;对于新增加的权限组列表项在原有列表项上方出现还有另外一种解决方法。我们可以通过权限组ID的升序排列来实现。案例33&#xff1a;更新列表数据但是&#xff0c;只增加按“GroupID”列升序排序的动作并不能解决问题。因为&#xff0c;我们每次【添加…

SharePoint 2013 DateTime字段查询

SharePoint 中对DateTime字段的查询需要主要以下两点&#xff1a; 1、参数值需要转换 DateTime tiem DateTime.Parse("2017-11-29"); var sTime SPUtility.CreateISO8601DateTimeFromSystemDateTime(tiem); 2、Caml语句需要加查询字段的Value需要加IncludeTimeV…

ubuntu c++ 实现自动回车键功能_苹果笔记本上怎么实现排队自动下载功能

用户在下载多个文件时&#xff0c;当然会希望这些文件都能同时下载&#xff0c;以达到短时间内完成下载任务的目的。但另一方面来说&#xff0c;同时下载过多文件&#xff0c;会分散带宽资源&#xff0c;降低了每个文件的下载速度&#xff0c;从而导致下载时间的延长。为了实现…

SharePoint 2013 列表(代码篇)

环境&#xff1a;Windows Server 2012&#xff0c;SharePoint 2013 本文主要是针对SharePoint里面《列表》的介绍&#xff0c;以及怎么用代码自定义列表&#xff0c;都是入门级的东西&#xff0c;主要是对自己学过的东西做一个总结。同时&#xff0c;希望对刚入坑的你有所帮助…

mysql 主从_mysql主从复制原理

0、为什么需要主从复制&#xff1f;1、在业务复杂的系统中&#xff0c;有这么一个情景&#xff0c;有一句sql语句需要锁表&#xff0c;导致暂时不能使用读的服务&#xff0c;那么就很影响运行中的业务&#xff0c;使用主从复制&#xff0c;让主库负责写&#xff0c;从库负责读&…

SharePoint 2013 网站模板打包和根据模板建站

环境&#xff1a;Windows Server 2012&#xff0c;SharePoint 2013 网站模板打包 1、在SharePoin Designer 允许保存成模板 SaveSiteAsTemplateEnabled true 2、点击网站的右上角的小齿轮→网站设置 3、点击保存网站为模板 4、在保存模板页面填写模板文件名称、模板…