ASP.NET的网站NPOI转EXCEL,转DataTable

<p>
NPOI一直都是ASP.NET网站所使用的DataTable转EXCEL,或者Excel转DataTable </p><p>以下是具体代码,它需要最新版的NPOI动态连接库,</p><p>这个是下载地址</p><p>http://down.51cto.com/data/695728</p>
 
 
 
 
 
 
 
 
using System;
using System.Web;
using System.Text;
using System.Data;
using System.IO;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;


namespace Admin.Common
{
    public class Common
    {
        private static Common common = null;
        public static Common getInstance() 
        {
            if (common == null) 
            {
                common = new Common();
            }
            return common;
        }


        /// 第一种  DataTable 转换成 Excel
        /// </summary> 
        public string WriteToExcel(DataTable dt)
        {
            //创建保存的路径(每天一个文件夹)
            string fn = string.Empty;
            string filename = "/TempFiles/" + DateTime.Now.ToString("yyyyMMdd") + "/";
            string path = HttpContext.Current.Server.MapPath(filename);
            try
            {
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                //删除近10天的文件夹
                try
                {
                    for (int i = 20; i > 0; i--)
                    {
                        string path2 = HttpContext.Current.Server.MapPath("/TempFiles/" + DateTime.Now.AddDays(-i).ToString("yyyyMMdd") + "/");
                        if (Directory.Exists(path2))
                        {
                            Directory.Delete(path2, true);
                        }
                    }
                }
                catch { }


                fn = "ENGUO会员信息_" + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss") + ".xls";
                path += fn;




                //创建工作薄
                XSSFWorkbook workbook = new XSSFWorkbook();
                //创建sheet表
                ISheet sheet = workbook.CreateSheet("sheet1");
                //设置单元格宽度
                sheet.SetColumnWidth(0, 20 * 256);
                sheet.SetColumnWidth(1, 28 * 256);
                sheet.SetColumnWidth(2, 28 * 256);
                sheet.SetColumnWidth(3, 25 * 256);


                //创建列的属性,高为:20*20
                IRow headerRow = sheet.CreateRow(0);
                headerRow.Height = 20 * 20;


                //创建列
                foreach (DataColumn column in dt.Columns)
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);


                //构建表格里的内容
                int rowIndex = 1;
                foreach (DataRow row in dt.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);
                    foreach (DataColumn column in dt.Columns)
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                    }
                    rowIndex++;
                }






                //使用文件流,写入磁盘
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    fs.Flush();
                    workbook.Write(fs);
                }


                StreamWriter sw = new StreamWriter(path + "success.log", false, Encoding.UTF8);
                sw.Write("下载成功!地址为:" + path + fn);
                sw.Flush();
                sw.Close();
            }
            catch (Exception e)
            {
                StreamWriter sw = new StreamWriter(path + "error.log", false, Encoding.UTF8);
                sw.Write("错误信息:" + e.Message + "\r\n  错误跟踪:" + e.StackTrace);
                sw.Flush();
                sw.Close();
            }
            //返回文件的磁盘路径
            return filename + fn;
        }


        /// <summary>
        /// 第二种  DataTable 转换成 Excel
        /// </summary>   
        public string ExportDataTableToExcel(DataTable dt)
        {


            //创建工作薄
            XSSFWorkbook wb = new XSSFWorkbook();
            //创建表
            ISheet sh = wb.CreateSheet("人员信息表");
            //设置单元格宽度
            sh.SetColumnWidth(0, 20 * 256);
            sh.SetColumnWidth(1, 28 * 256);
            sh.SetColumnWidth(2, 28 * 256);
            sh.SetColumnWidth(3, 25 * 256);


            IRow row1 = sh.CreateRow(0);
            row1.Height = 20 * 20;


            ICell icell1top = row1.CreateCell(0);
            icell1top.CellStyle = Getcellstyle(wb, stylexls.文本);
            icell1top.SetCellValue("一");


            ICell icell2top = row1.CreateCell(1);
            icell2top.CellStyle = Getcellstyle(wb, stylexls.文本);
            icell2top.SetCellValue("二");


            ICell icell3top = row1.CreateCell(2);
            icell3top.CellStyle = Getcellstyle(wb, stylexls.文本);
            icell3top.SetCellValue("三");


            ICell icell4top = row1.CreateCell(3);
            icell4top.CellStyle = Getcellstyle(wb, stylexls.文本);
            icell4top.SetCellValue("TID");


            string[] column = { "一", "二", "三", "TID" };


            if (dt != null && dt.Rows.Count > 0)
            {
                string iden = string.Empty;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    IRow row = sh.CreateRow(i + 1);
                    row.Height = 20 * 20;


                    for (int j = 0; j < column.Length; j++)
                    {
                        ICell cell = row.CreateCell(j);
                        cell.CellStyle = Getcellstyle(wb, stylexls.文本);
                        cell.SetCellValue(dt.Rows[i][column[j]].ToString());
                    }
                }
            }
            string virtualpath = "/AdminSystem/TempFiles/";
            string path = HttpContext.Current.Server.MapPath(virtualpath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filename = "表名-" + DateTime.Now.ToString("yyyyMMddhhmmssfffffff") + ".xls";
            using (FileStream stm = new FileStream((path + filename), FileMode.Create, FileAccess.Write))
            {
                stm.Flush();
                wb.Write(stm);
            }
            return virtualpath + filename;
        }


        #region 定义单元格常用到的样式枚举
        private enum stylexls
        {
            文本,
            内容,
            时间,
            数字,
            百分比,
            科学计数法,
            默认
        }
        #endregion


        #region 定义单元格常用到的样式
        private static ICellStyle Getcellstyle(IWorkbook wb, stylexls str)
        {
            ICellStyle cellStyle = wb.CreateCellStyle();


            //定义字体
            IFont font12 = wb.CreateFont();
            font12.FontHeightInPoints = 12;
            font12.FontName = "微软雅黑";


            IFont font10 = wb.CreateFont();
            font10.FontHeightInPoints = 10;
            font10.FontName = "微软雅黑";


            IFont font13 = wb.CreateFont();
            font13.FontHeightInPoints = 20;
            font13.FontName = "微软雅黑";


            IFont font = wb.CreateFont();
            font.FontName = "微软雅黑";


            //定义边框
            cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;


            //背景颜色
            cellStyle.FillBackgroundColor = (short)new XSSFColor().Theme;


            //水平对齐
            cellStyle.Alignment = HorizontalAlignment.Center;


            //垂直对齐
            cellStyle.VerticalAlignment = VerticalAlignment.Center;


            //自动换行
            cellStyle.WrapText = true;


            switch (str)
            {
                case stylexls.文本:
                    cellStyle.SetFont(font12);
                    break;
                case stylexls.内容:
                    cellStyle.SetFont(font10);
                    break;
                case stylexls.时间:
                    IDataFormat datastyle = wb.CreateDataFormat();
                    cellStyle.DataFormat = datastyle.GetFormat("yyyy-MM-dd");
                    cellStyle.SetFont(font);
                    break;
                case stylexls.默认:
                    cellStyle.SetFont(font13);
                    break;
            }
            return cellStyle;
        }
        #endregion


    }
}


 

 
 



你可能感兴趣的:(asp.net)