C# MVC使用NPOI导出Excel

C# MVC使用NPOI导出Excel

导出Excel方法


        /// <summary>
        /// 导出excel
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="searchkey"></param>
        /// <returns></returns>
        public FileResult exprotexcel(string dt_begin, string dt_end, string title, string searchkey)
        {
            #region 获取数据
            string sError = "";
            List<DepartmentDetails> data = PublicBll.GetDepartmentDetailsAll(dt_begin, dt_end, ref sError);
            }
            #endregion
            //设置表头
            Dictionary<string, string> collection = new Dictionary<string, string>();
            collection.Add("dt_OperDate", "时间");
            collection.Add("companyname", "餐厅名称");
            collection.Add("vch_dishname", "菜单");
            collection.Add("num_cost", "订单总价");
            collection.Add("num_discount", "补贴金额");
            collection.Add("num_ys", "实收金额");
            collection.Add("member_name", "用餐人姓名");
            collection.Add("vch_id", "身份证号码");
            collection.Add("area", "区域");
            collection.Add("age", "年龄");
            collection.Add("diningStyle", "就餐方式");
            collection.Add("vch_empname", "点餐员");
            collection.Add("vch_tel", "点餐员手机号");
            collection.Add("location", "点餐位置");

            var byteInfo = ExportExcel<DepartmentDetails>(collection, data, searchkey);
            return File(byteInfo, "application/vnd.ms-excel", string.Format("{0}-{1}.xls", title, DateTime.Now.ToString("yyyyMMddHHmm")));
        }

公共部分

		/// <summary>
        /// NPOI导出EXCEl公共部分
        /// </summary>
        /// <param name="sheetName">工作表名</param>
        /// <param name="arrHead">表头</param>
        /// <param name="arrColWidth">列宽</param>
        /// <param name="headHeight">表头高度</param>
        /// <param name="colHeight">列高度</param>
        /// <param name="dataSource">数据</param>
        /// <param name="title">表头标题</param>
        /// <param name="footer">底部内容</param>
        public static byte[] ExportExcel<T>(Dictionary<string, string> columnsHeader, List<T> dataSource, string title = null, string footer = null)
        {
            IWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("Sheet1");
            sheet.DefaultColumnWidth = 18;

            IRow row;
            ICell cell;

            #region excel标题头
            int rowIndex = 0;
            if (!string.IsNullOrEmpty(title))
            {
                ICellStyle cellStyle = workbook.CreateCellStyle();
                cellStyle.VerticalAlignment = VerticalAlignment.CENTER;
                cellStyle.Alignment = HorizontalAlignment.CENTER;
                IFont font = workbook.CreateFont();
                font.FontHeightInPoints = 12;
                font.Boldweight = 700;
                cellStyle.SetFont(font);
                var region = new CellRangeAddress(0, 0, 0, columnsHeader.Keys.Count > 0 ? columnsHeader.Keys.Count - 1 : 0);
                sheet.AddMergedRegion(region);
                //合并单元格后样式
                ((HSSFSheet)sheet).SetEnclosedBorderOfRegion(region, BorderStyle.THIN, NPOI.HSSF.Util.HSSFColor.BLACK.index);

                row = sheet.CreateRow(rowIndex);
                row.HeightInPoints = 20;
                cell = row.CreateCell(0);
                cell.SetCellValue(title);
                cell.CellStyle = cellStyle;
                rowIndex++;
            }
            #endregion

            #region 列头
            row = sheet.CreateRow(rowIndex);
            row.HeightInPoints = 15;
            int cellIndex = 0;
            foreach (var value in columnsHeader.Values)
            {
                ICellStyle cellStyle = workbook.CreateCellStyle();
                cellStyle = workbook.CreateCellStyle();
                cellStyle.BorderBottom = BorderStyle.THIN;
                cellStyle.BorderLeft = BorderStyle.THIN;
                cellStyle.BorderRight = BorderStyle.THIN;
                cellStyle.BorderTop = BorderStyle.THIN;
                //背景色
                cellStyle.FillForegroundColor = HSSFColor.GREY_25_PERCENT.index;
                cellStyle.FillPattern = FillPatternType.SOLID_FOREGROUND;
                //水平垂直居中
                cellStyle.VerticalAlignment = VerticalAlignment.CENTER;
                cellStyle.Alignment = HorizontalAlignment.CENTER;
                IFont font = workbook.CreateFont();
                font.FontHeightInPoints = 10;
                font.Boldweight = 700;
                cellStyle.SetFont(font);

                cell = row.CreateCell(cellIndex);
                cell.CellStyle = cellStyle;
                cell.SetCellValue(value);
                cellIndex++;
            }
            rowIndex++;
            #endregion

            #region 主题内容

            //单元格样式 注:不要放循环里面,NPOI中调用workbook.CreateCellStyle()方法超过4000次会报错
            ICellStyle contentStyle = workbook.CreateCellStyle();
            contentStyle.BorderBottom = BorderStyle.THIN;
            contentStyle.BorderLeft = BorderStyle.THIN;
            contentStyle.BorderRight = BorderStyle.THIN;
            contentStyle.BorderTop = BorderStyle.THIN;
            contentStyle.VerticalAlignment = VerticalAlignment.CENTER;
            IFont contentFont = workbook.CreateFont();
            contentFont.FontHeightInPoints = 10;
            contentStyle.SetFont(contentFont);

            //日期格式样式
            ICellStyle dateStyle = workbook.CreateCellStyle();
            dateStyle.BorderBottom = BorderStyle.THIN;
            dateStyle.BorderLeft = BorderStyle.THIN;
            dateStyle.BorderRight = BorderStyle.THIN;
            dateStyle.BorderTop = BorderStyle.THIN;
            dateStyle.VerticalAlignment = VerticalAlignment.CENTER;
            dateStyle.SetFont(contentFont);
            IDataFormat format = workbook.CreateDataFormat();
            dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd HH:mm:ss");
            foreach (T item in dataSource)
            {
                row = sheet.CreateRow(rowIndex);
                row.HeightInPoints = 15;
                rowIndex++;
                Type type = item.GetType();
                PropertyInfo[] properties = type.GetProperties();
                if (properties.Length > 0)
                {
                    cellIndex = 0;
                    foreach (var key in columnsHeader.Keys)
                    {
                        cell = row.CreateCell(cellIndex);
                        cell.CellStyle = contentStyle;

                        if (properties.Select(x => x.Name.ToLower()).Contains(key.ToLower()))
                        {
                            var property = properties.Where(x => x.Name.ToLower() == key.ToLower()).FirstOrDefault();
                            string drValue = property.GetValue(item) == null ? "" : property.GetValue(item).ToString();
                            //当类型类似DateTime?时
                            var fullType = property.PropertyType.Name == "Nullable`1" ? property.PropertyType.GetGenericArguments()[0].FullName : property.PropertyType.FullName;
                            switch (fullType)
                            {
                                case "System.String": //字符串类型
                                    cell.SetCellValue(drValue);
                                    break;
                                case "System.DateTime": //日期类型
                                    if (string.IsNullOrEmpty(drValue) || drValue == "0001/1/1 0:00:00")
                                    {
                                        cell.SetCellValue("");
                                    }
                                    else
                                    {
                                        DateTime dateV;
                                        DateTime.TryParse(drValue, out dateV);
                                        cell.SetCellValue(dateV);

                                        cell.CellStyle = dateStyle; //格式化显示
                                    }
                                    break;
                                case "System.Boolean": //布尔型
                                    bool boolV = false;
                                    bool.TryParse(drValue, out boolV);
                                    cell.SetCellValue(boolV);
                                    break;
                                case "System.Int16": //整型
                                case "System.Int32":
                                case "System.Int64":
                                case "System.Byte":
                                    int intV = 0;
                                    int.TryParse(drValue, out intV);
                                    cell.SetCellValue(intV);
                                    break;
                                case "System.Decimal": //浮点型
                                case "System.Double":
                                    double doubV = 0;
                                    double.TryParse(drValue, out doubV);
                                    cell.SetCellValue(doubV);
                                    break;
                                case "System.DBNull": //空值处理
                                    cell.SetCellValue("");
                                    break;
                                default:
                                    cell.SetCellValue("");
                                    break;
                            }
                        }
                        cellIndex++;
                    }
                }

            }
            #endregion

            #region 结尾行
            if (!string.IsNullOrEmpty(footer))
            {
                ICellStyle cellStyle = workbook.CreateCellStyle();
                cellStyle.VerticalAlignment = VerticalAlignment.CENTER;
                cellStyle.Alignment = HorizontalAlignment.CENTER;
                IFont font = workbook.CreateFont();
                font.FontHeightInPoints = 10;
                font.Boldweight = 700;
                cellStyle.SetFont(font);
                var region = new CellRangeAddress(rowIndex, rowIndex, 0, columnsHeader.Keys.Count > 0 ? columnsHeader.Keys.Count - 1 : 0);
                sheet.AddMergedRegion(region);
                //合并单元格后样式
                ((HSSFSheet)sheet).SetEnclosedBorderOfRegion(region, BorderStyle.THIN, NPOI.HSSF.Util.HSSFColor.BLACK.index);

                row = sheet.CreateRow(rowIndex);
                row.HeightInPoints = 18;
                cell = row.CreateCell(0);
                cell.SetCellValue(footer);
                cell.CellStyle = cellStyle;
            }
            #endregion

            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                return ms.ToArray();
                //或者直接导出不用返回值  var response = System.Web.HttpContext.Current.Response;
                //response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                //response.ContentType = "application/vnd.ms-excel";
                //response.AddHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
                //response.BinaryWrite(ms.ToArray());
                //response.Buffer = true;
                //response.Flush();
                //response.End();
            }
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用NPOI可以很方便地在Winform应用程序中导出Excel文件。 首先,我们需要将NPOI引用添加到Winform项目中。可以通过NuGet包管理器或手动引用方式添加。 然后,我们需要创建一个工作簿对象,并添加一个工作表。可以使用HSSFWorkbook或XSSFWorkbook类来创建工作簿对象,分别对应xls和xlsx格式的Excel文件。 接下来,我们可以向工作表中添加数据。可以使用工作表中的创建行对象,然后为每行添加单元格数据。可以设置单元格的值、格式、样式等属性。 最后,我们需要将工作簿保存为Excel文件。可以使用FileStream类创建一个文件流对象,并使用工作簿的Write方法将数据写入到文件流中。 以下是一个简单的示例代码,将一个包含学生信息的列表导出Excel文件: ```csharp using System; using System.Collections.Generic; using System.IO; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; // 创建工作簿和工作表 HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("学生信息"); // 添加表头 IRow headerRow = sheet.CreateRow(0); headerRow.CreateCell(0).SetCellValue("学号"); headerRow.CreateCell(1).SetCellValue("姓名"); headerRow.CreateCell(2).SetCellValue("年龄"); // 添加数据 List<Student> students = GetStudents(); for (int i = 0; i < students.Count; i++) { IRow dataRow = sheet.CreateRow(i + 1); dataRow.CreateCell(0).SetCellValue(students[i].Id); dataRow.CreateCell(1).SetCellValue(students[i].Name); dataRow.CreateCell(2).SetCellValue(students[i].Age); } // 保存为Excel文件 using (FileStream fileStream = new FileStream("学生信息.xls", FileMode.Create)) { workbook.Write(fileStream); } ``` 在这个示例中,我们首先创建了一个工作簿和一个工作表,并添加了表头。然后,通过获取学生信息列表来添加数据。最后,我们将工作簿保存为名为“学生信息.xls”的Excel文件。 这样,使用NPOI就可以在Winform应用程序中导出Excel文件。希望可以对你有所帮助! ### 回答2: 使用WinForm搭配NPOI导出Excel非常简单。首先,我们需要在WinForm中添加对NPOI的引用。可以通过NuGet包管理器来导入NPOI库。 导入库后,我们可以创建一个DataGridView控件来展示需要导出的数据,或者直接在代码中定义一个DataTable对象来储存数据。然后,在按钮的Click事件处理程序中编写导出Excel的代码。 以下是一个简单的示例: 1. 添加一个DataGridView控件(或创建DataTable对象)并加载需要导出的数据。 2. 在按钮的Click事件中添加以下代码: ```csharp using NPOI.XSSF.UserModel; // 导入XSSF命名空间 using NPOI.SS.UserModel; // 导入SS命名空间 using NPOI.HSSF.Util; // 导入HSSFUtil命名空间 using NPOI.HSSF.UserModel; // 导入HSSFUserModel命名空间 using NPOI.SS.Util; // 导入SSUtil命名空间 using NPOI.HPSF; // 导入HPSF命名空间 using NPOI.POIFS.FileSystem; // 导入POIFS命名空间 // 创建一个Excel文档对象 XSSFWorkbook workbook = new XSSFWorkbook(); // 创建一个工作表对象 ISheet sheet = workbook.CreateSheet("Sheet1"); // 创建行和单元格 IRow row = sheet.CreateRow(0); for (int i = 0; i < dataGridView1.Columns.Count; i++) { row.CreateCell(i).SetCellValue(dataGridView1.Columns[i].HeaderText); } // 填充数据 for (int i = 0; i < dataGridView1.Rows.Count; i++) { row = sheet.CreateRow(i + 1); for (int j = 0; j < dataGridView1.Columns.Count; j++) { row.CreateCell(j).SetCellValue(dataGridView1.Rows[i].Cells[j].Value.ToString()); } } // 保存文件 SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Excel文件|*.xlsx"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { using (FileStream fs = new FileStream(saveFileDialog.FileName, FileMode.Create)) { workbook.Write(fs); } } // 提示导出成功 MessageBox.Show("导出成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); ``` 这是一个基本的WinForm使用NPOI导出Excel的代码示例。你可以根据自己的需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值