• 导出使用NPOI


    调用:

     DataTable table = new DataTable();
                #region 创建 datatable
                table.Columns.Add(new DataColumn("账号", typeof(string)));
                table.Columns.Add(new DataColumn("姓名", typeof(string)));
                #endregion
    
                #region 填充数据
                DataRow row = null;
                foreach (var item in list)
                {
                    row = table.NewRow();
                    row[0] = item.Account;
                    row[1] = item.Name;
                    table.Rows.Add(row);
                } 
                #endregion
    
                return ExportExcelBase(table, "导出测试");

    基类:

    /// <summary>
            /// 
            /// </summary>
            /// <param name="table">datatable</param>
            /// <param name="fileName">文件名称</param>
            /// <param name="strHeaderText">表头文本</param>
            /// <returns></returns>
            [NonAction]
            protected FileContentResult ExportExcelBase(DataTable table, string fileName, string strHeaderText = null)
            {
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                }
                else
                {
                    fileName = fileName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                }
                string headerName = strHeaderText ?? fileName;
                if (string.Compare(Request.Browser.Browser, "IE", true) == 0 ||
                   string.Compare(Request.Browser.Browser, "InternetExplorer", true) == 0)//ie 需要编码
                {
                    fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
                }
    return File(ExportExcelFromDataTable(table, headerName).GetBuffer(),
                    "application/vnd.ms-excel", fileName);
            }

    以下方法从网上找来:

    /// <summary>
            /// DataTable导出到Excel的MemoryStream
            /// </summary>
            /// <param name="dtSource">源DataTable</param>  
            /// <param name="strHeaderText">表头文本</param>  
            /// <returns></returns>
            public MemoryStream ExportExcelFromDataTable(DataTable dtSource, string strHeaderText = null)
            {
                var workbook = new HSSFWorkbook();
                var sheet = workbook.CreateSheet();
    
                #region 右击文件 属性信息
                //{  
                //    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();  
                //    dsi.Company = "http://www.yongfa365.com/";  
                //    workbook.DocumentSummaryInformation = dsi;  
    
                //    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();  
                //    si.Author = "柳永法"; //填加xls文件作者信息  
                //    si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息  
                //    si.LastAuthor = "柳永法2"; //填加xls文件最后保存者信息  
                //    si.Comments = "说明信息"; //填加xls文件作者信息  
                //    si.Title = "NPOI测试"; //填加xls文件标题信息  
                //    si.Subject = "NPOI测试Demo";//填加文件主题信息  
                //    si.CreateDateTime = DateTime.Now;  
                //    workbook.SummaryInformation = si;  
                //}
                #endregion
    
                var dateStyle = workbook.CreateCellStyle();
                var format = workbook.CreateDataFormat();
                dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
    
                //取得列宽  
                var arrColWidth = new int[dtSource.Columns.Count];
                foreach (DataColumn item in dtSource.Columns)
                {
                    arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
                }
                for (int i = 0; i < dtSource.Rows.Count; i++)
                {
                    for (int j = 0; j < dtSource.Columns.Count; j++)
                    {
                        int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                        if (intTemp > arrColWidth[j])
                        {
                            arrColWidth[j] = intTemp;
                        }
                    }
                }
    
    
    
                int rowIndex = 0;
    
                foreach (DataRow row in dtSource.Rows)
                {
                    #region 新建表,填充表头,填充列头,样式
                    if (rowIndex == 65535 || rowIndex == 0)
                    {
                        if (rowIndex != 0)
                        {
                            sheet = workbook.CreateSheet();
                        }
    
                        #region 表头及样式
                        {
                            var headerRow = sheet.CreateRow(0);
                            headerRow.HeightInPoints = 25;
                            headerRow.CreateCell(0).SetCellValue(strHeaderText);
    
                            var headStyle = workbook.CreateCellStyle();
                            headStyle.Alignment = HorizontalAlignment.Center;
                            var font = workbook.CreateFont();
                            font.FontHeightInPoints = 20;
                            font.Boldweight = 700;
                            headStyle.SetFont(font);
    
                            headerRow.GetCell(0).CellStyle = headStyle;
    
                            sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
                            //headerRow.Dispose();  
                        }
                        #endregion
    
    
                        #region 列头及样式
                        {
                            var headerRow = sheet.CreateRow(1);
    
    
                            var headStyle = workbook.CreateCellStyle();
                            headStyle.Alignment = HorizontalAlignment.Center;
                            var font = workbook.CreateFont();
                            font.FontHeightInPoints = 10;
                            font.Boldweight = 700;
                            headStyle.SetFont(font);
    
    
                            foreach (DataColumn column in dtSource.Columns)
                            {
                                headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                                headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
    
                                //设置列宽  
                                try
                                {
                                    sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
                                }
                                catch { }
    
                            }
                            //headerRow.Dispose();  
                        }
                        #endregion
    
                        rowIndex = 2;
                    }
                    #endregion
    
    
                    #region 填充内容
                    var dataRow = sheet.CreateRow(rowIndex);
                    foreach (DataColumn column in dtSource.Columns)
                    {
                        var newCell = dataRow.CreateCell(column.Ordinal);
    
                        var drValue = row[column].ToString();
    
                        switch (column.DataType.ToString())
                        {
                            case "System.String"://字符串类型  
                                newCell.SetCellValue(drValue);
                                break;
                            case "System.DateTime"://日期类型  
                                DateTime dateV;
                                DateTime.TryParse(drValue, out dateV);
                                newCell.SetCellValue(dateV);
    
                                newCell.CellStyle = dateStyle;//格式化显示  
                                break;
                            case "System.Boolean"://布尔型  
                                bool boolV = false;
                                bool.TryParse(drValue, out boolV);
                                newCell.SetCellValue(boolV);
                                break;
                            case "System.Int16"://整型  
                            case "System.Int32":
                            case "System.Int64":
                            case "System.Byte":
                                int intV = 0;
                                int.TryParse(drValue, out intV);
                                newCell.SetCellValue(intV);
                                break;
                            case "System.Decimal"://浮点型  
                            case "System.Double":
                                double doubV = 0;
                                double.TryParse(drValue, out doubV);
                                newCell.SetCellValue(doubV);
                                break;
                            case "System.DBNull"://空值处理  
                                newCell.SetCellValue("");
                                break;
                            default:
                                newCell.SetCellValue("");
                                break;
                        }
    
                    }
                    #endregion
    
                    rowIndex++;
                }
    
    
                using (var ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
    
                    // sheet.Dispose();  
                    //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet  
                    return ms;
                }
            }
  • 相关阅读:
    iOS:Objective-C中Self和Super详解
    调试工具Instruments----Core Animation
    iOS开发之复制字符串到剪贴板
    Copy 和 mutableCopy
    TCP/IP,Http,Socket,XMPP的区别
    iOS程序中的内存分配 栈区堆区全局区(转)
    iOS常见算法(二分法 冒泡 选择 快排)
    老司机带你走进Core Animation
    C# 爬虫小程序
    C# 房贷计算器
  • 原文地址:https://www.cnblogs.com/ly7454/p/3910668.html
Copyright © 2020-2023  润新知