封装了导出Excel完美解决类

namespace AC.EAS.Net.Web

{   

    /// <summary>

    /// Office操作类,主要用于导出Excel和Word

    /// </summary>

    public class OfficeHelper

    {

        #region 基本变量定义

 

        /// <summary>

        /// 填加Excel文件公司名称

        /// </summary>

        public static string CompanyName = string.Empty;

        /// <summary>

        /// 填加Excel文件作者信息

        /// </summary>

        public static string Author = string.Empty;

        /// <summary>

        /// 填加Excel文件创建程序信息

        /// </summary>

        public static string ApplicationName = string.Empty;

        /// <summary>

        /// 填加Excel文件最后保存者信息

        /// </summary>

        public static string LastAuthor = string.Empty;

        /// <summary>

        /// 填加Excel文件注释信息

        /// </summary>

        public static string Comments = string.Empty;

        /// <summary>

        /// 填加Excel文件标题信息

        /// </summary>

        public static string Title = string.Empty;

        /// <summary>

        /// 填加Excel文件主题信息

        /// </summary>

        public static string Subject = string.Empty;

        /// <summary>

        /// 表头行高,默认35个点

        /// </summary>

        public static int HeaderHeightInPoints = 35;

        /// <summary>

        /// 表头字体大小,默认16个点

        /// </summary>

        public static short HeaderFontHeightInPoints = 16;

        /// <summary>

        /// 表头字体的粗细程度,默认700

        /// </summary>

        public static short HeaderBoldweight = 700;

        /// <summary>

        /// 列头行高,默认19

        /// </summary>

        public static int ColumnHeadHeightInPoints = 19;

        /// <summary>

        /// 列头字体大小,默认10

        /// </summary>

        public static short ColumnHeadFontHeightInPoints = 10;

        /// <summary>

        /// 数据行行高,默认16

        /// </summary>

        public static int DataHeightInPoints = 16;

        /// <summary>

        /// 需要生成货币格式的列索引,目前只支持一列

        /// </summary>

        public static int MonetaryCell = 0;

        /// <summary>

        /// 是否需要生成货币格式

        /// </summary>

        public static bool BoolMonetary = false;

        /// <summary>

        /// 实例化一个工作簿

        /// </summary>

        public static HSSFWorkbook workbook = new HSSFWorkbook();

 

        #endregion

 

        public OfficeHelper() { }

 

        #region 给Excel单元格加边框

 

        /// <summary>

        /// 给Excel单元格加边框

        /// </summary>

        /// <returns>返回单元格边框样式</returns>

        public static HSSFCellStyle getCellStyle(HSSFCellStyle cellStyle, NPOI.HSSF.UserModel.CellBorderType CellBorderType)

        {

            cellStyle = workbook.CreateCellStyle();

            cellStyle.BorderBottom = CellBorderType;

            cellStyle.BorderLeft = CellBorderType;

            cellStyle.BorderRight = CellBorderType;

            cellStyle.BorderTop = CellBorderType;

            return cellStyle;

        }

 

        #endregion

 

        #region 从DataTable中将数据导出到Excel

        /// <summary>

        /// 从DataTable中将数据导出到Excel

        /// </summary>

        /// <param name="dtSource">数据源</param>

        /// <param name="strHeaderText">Excel标题</param>

        /// <returns>返回内存流中的数据信息</returns>

        public static MemoryStream Export(DataTable dtSource, string strHeaderText)

        {

            //创建一张Sheet表

            HSSFSheet sheet = workbook.CreateSheet();

 

            #region Excel工表簿图标右击文件属性信息

 

            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();

            dsi.Company = CompanyName;

            workbook.DocumentSummaryInformation = dsi;

            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();

            si.Author = Author;

            si.ApplicationName = ApplicationName;

            si.LastAuthor = LastAuthor;

            si.Comments = Comments;

            si.Title = Title;

            si.Subject = Subject;

            si.CreateDateTime = DateTime.Now;

            workbook.SummaryInformation = si;

 

            #endregion

 

            //创建单元格样式

            HSSFCellStyle cellStyle = workbook.CreateCellStyle();

 

            #region 取得列宽

 

            int[] 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;

                    }

                }

            }

 

            #endregion

 

            //行索引

            int rowIndex = 0;

 

            #region 新建表,填充表头,填充列头,样式

            foreach (DataRow row in dtSource.Rows)

            {

                if (rowIndex == 65535 || rowIndex == 0)

                {

                    if (rowIndex != 0)

                    {

                        sheet = workbook.CreateSheet();

                    }

 

                    #region 表头及样式

                    {

                        HSSFRow headerRow = sheet.CreateRow(0);

                        headerRow.HeightInPoints = HeaderHeightInPoints;

                        headerRow.CreateCell(0).SetCellValue(strHeaderText);

 

                        HSSFCellStyle headStyle = workbook.CreateCellStyle();

                        headStyle.Alignment = CellHorizontalAlignment.CENTER;

                        headStyle.VerticalAlignment = CellVerticalAlignment.CENTER;

 

                        HSSFFont font = workbook.CreateFont();

                        font.FontHeightInPoints = HeaderFontHeightInPoints;

                        font.Boldweight = HeaderBoldweight;

                        headStyle.SetFont(font);

 

                        headerRow.GetCell(0).CellStyle = headStyle;

 

                        sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));

                        headerRow.Dispose();

                    }

                    #endregion

 

                    #region 列头及样式

                    {

                        HSSFRow headerRow = sheet.CreateRow(1);

                        headerRow.HeightInPoints = ColumnHeadHeightInPoints;

 

                        HSSFCellStyle headStyle = workbook.CreateCellStyle();

                        headStyle = getCellStyle(headStyle, CellBorderType.THIN);

                        headStyle.Alignment = CellHorizontalAlignment.LEFT;

                        headStyle.VerticalAlignment = CellVerticalAlignment.CENTER;

 

                        HSSFFont font = workbook.CreateFont();

                        font.FontHeightInPoints = ColumnHeadFontHeightInPoints;

                        headStyle.SetFont(font);

 

                        foreach (DataColumn column in dtSource.Columns)

                        {

                            headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);

                            headerRow.GetCell(column.Ordinal).CellStyle = headStyle;

 

                            //设置列宽  

                            sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);

                        }

                        headerRow.Dispose();

                    }

                    #endregion

 

                    rowIndex = 2;

                }

 

                #region 填充内容

                HSSFRow dataRow = sheet.CreateRow(rowIndex);

                dataRow.HeightInPoints = DataHeightInPoints;

 

                foreach (DataColumn column in dtSource.Columns)

                {

                    HSSFCell newCell = dataRow.CreateCell(column.Ordinal);

 

                    //cellStyle = getCellStyle(cellStyle, CellBorderType.THIN);

                    //newCell.CellStyle = cellStyle;

 

                    string 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);

                            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":

                        case "System.Float":

                            double doubV = 0;

                            double.TryParse(drValue, out doubV);

                            newCell.SetCellValue(doubV);

 

                            if (BoolMonetary == true)

                            {

                                HSSFCell cell2 = sheet.CreateRow(rowIndex).CreateCell(MonetaryCell);

                                cell2.SetCellValue(doubV);

                                HSSFCellStyle cellStyle2 = workbook.CreateCellStyle();

                                HSSFDataFormat format = workbook.CreateDataFormat();

                                cellStyle2.DataFormat = format.GetFormat("¥#,##0");

                                cellStyle2 = getCellStyle(cellStyle2, CellBorderType.THIN);

                                cell2.CellStyle = cellStyle2;

                            }

                            break;

                        //空值处理  

                        case "System.DBNull":

                            newCell.SetCellValue("");

                            break;

                        default:

                            newCell.SetCellValue("");

                            break;

                    }

                }

                #endregion

                rowIndex++;

            }

            using (MemoryStream ms = new MemoryStream())

            {

                workbook.Write(ms);

                ms.Flush();

                ms.Position = 0;

 

                sheet.Dispose();

                //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet  

                return ms;

            }

            #endregion

        }

 

        #region 用于Web导出

        /// <summary>  

        /// 用于Web导出  

        /// </summary>  

        /// <param name="dtSource">源DataTable</param>  

        /// <param name="strHeaderText">表头文本</param>  

        /// <param name="strFileName">文件名</param>

        public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName)

        {

 

            HttpContext curContext = HttpContext.Current;

 

            // 设置编码和附件格式  

            curContext.Response.ContentType = "application/vnd.ms-excel";

            curContext.Response.ContentEncoding = Encoding.UTF8;

            curContext.Response.Charset = "";

            curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));

 

            curContext.Response.BinaryWrite(Export(dtSource, strHeaderText).GetBuffer());

            curContext.Response.End();

 

        }

        #endregion

        #endregion

    }

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值