一个导出Excel的类

需要引入

using NPOI.HSSF.UserModel;

 public class ExcelHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt">需要导出的DataTable</param>
        /// <param name="ColName">导出的表格列名</param>
        /// <param name="Filename">导出的表格文件名称_默认当前日期不带时间_注:文件名不能有:号</param>
        /// <param name="Sheetname">导出的Sheet名</param>
        /// <returns>成功返回_异常返回-1</returns>
        public int OutPutExcelByDataTable(DataTable dt, List<string> ColName, string Filename = "", string Sheetname = "")
        {
            try
            {
                HSSFWorkbook workbook = new HSSFWorkbook();
                string sheetname = Sheetname != "" ? Sheetname : dt.TableName;
                NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet(sheetname);
                NPOI.SS.UserModel.IRow r0 = sheet.CreateRow(0);
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (ColName.Count > i)
                    {
                        r0.CreateCell(i).SetCellValue(ColName[i]);
                    }
                    else
                    {
                        r0.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
                    }
                }
                int k = 1;
                foreach (DataRow row in dt.Rows)
                {
                    NPOI.SS.UserModel.IRow Row = sheet.CreateRow(k);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Row.CreateCell(j).SetCellValue(row[j].ToString());
                    }
                    k++;
                }
                dt = null;
                using (MemoryStream ms = new MemoryStream())
                {
                    workbook.Write(ms);
                    string filename = Filename != "" ? Filename : DateTime.Now.Date.ToShortDateString();
                    HttpContext.Current.Response.ContentType = "application/x-excel";
                    HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
                    HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                    HttpContext.Current.Response.End();
                    return 0;
                }
            }
            catch
            { return -1; }

        }
    }

 

posted @ 2013-07-24 10:55  不要用我的二来伤害我  阅读(298)  评论(0编辑  收藏  举报