C# Excel操作辅助类(需下载NPOI组件,见代码顶部注释)

分类:C#     发布:2019-08-16     来源:本站     浏览:923 次
//--------------------------------------------------------------------------------
// 文件描述:Excel辅助类
// 文件作者:全体开发人员
// 特别说明:需使用NPOI组件,组件下载地址:http://file.qingshanboke.com/File/Preview/96c45bc7bd0c4b33bd5c1a7906b9b1f4
// 创建日期:2016-06-27
//--------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;

namespace RC.Framework.Helper
{
    public class ExcelHelper
    {
        public static string BasePath
        {
            get { return VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath); }
        }

        /// <summary>
        ///     将DataTable导出到Excel,返回文件的web路径
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static string ExportDataTableToExcel(DataTable dt, string fileName)
        {
            #region 表头

            var hssfworkbook = new HSSFWorkbook();
            var hssfSheet = hssfworkbook.CreateSheet(fileName);
            hssfSheet.DefaultColumnWidth = 20;
            hssfSheet.SetColumnWidth(0, 35 * 256);
            hssfSheet.SetColumnWidth(3, 20 * 256);
            // 表头
            var tagRow = hssfSheet.CreateRow(0);
            tagRow.Height = 22 * 20;

            // 标题样式
            var cellStyle = hssfworkbook.CreateCellStyle();
            cellStyle.Alignment = HSSFCellStyle.ALIGN_CENTER;
            cellStyle.VerticalAlignment = HSSFCellStyle.VERTICAL_CENTER;
            cellStyle.BorderBottom = HSSFCellStyle.BORDER_THIN;
            cellStyle.BorderBottom = HSSFCellStyle.BORDER_THIN;
            cellStyle.BottomBorderColor = HSSFColor.BLACK.index;
            cellStyle.BorderLeft = HSSFCellStyle.BORDER_THIN;
            cellStyle.LeftBorderColor = HSSFColor.BLACK.index;
            cellStyle.BorderRight = HSSFCellStyle.BORDER_THIN;
            cellStyle.RightBorderColor = HSSFColor.BLACK.index;
            cellStyle.BorderTop = HSSFCellStyle.BORDER_THIN;
            cellStyle.TopBorderColor = HSSFColor.BLACK.index;
            //NPOI.SS.UserModel.Font font = hssfworkbook.CreateFont();
            //font.Boldweight = 30 * 20;
            //font.FontHeight = 12 * 20;
            //cellStyle.SetFont(font);

            int colIndex;
            for (colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
            {
                tagRow.CreateCell(colIndex).SetCellValue(dt.Columns[colIndex].ColumnName);
                tagRow.GetCell(colIndex).CellStyle = cellStyle;
            }

            #endregion

            #region 表数据

            // 表数据 
            for (var k = 0; k < dt.Rows.Count; k++)
            {
                var dr = dt.Rows[k];
                var row = hssfSheet.CreateRow(k + 1);
                for (var i = 0; i < dt.Columns.Count; i++)
                {
                    row.CreateCell(i).SetCellValue(dr[i].ToString());
                    row.GetCell(i).CellStyle = cellStyle;
                }
            }

            #endregion

            var path = HttpContext.Current.Server.MapPath("~/UploadFiles/Export");
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            using (var file = new FileStream(Path.Combine(path, fileName), FileMode.Create))
            {
                hssfworkbook.Write(file);
                file.Close();
            }

            return string.Format("{0}UploadFiles/Export/{1}", BasePath, fileName);
        }

        /// <summary>
        ///     将DataSet导出到Excel,返回文件的web路径
        /// </summary>
        /// <param name="set">DataTable</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static string ExportDataTableToExcel(List<DataTable> set, string fileName)
        {
            var hssfworkbook = new HSSFWorkbook();

            // 标题样式
            var cellStyle = hssfworkbook.CreateCellStyle();
            cellStyle.Alignment = HSSFCellStyle.ALIGN_CENTER;
            cellStyle.VerticalAlignment = HSSFCellStyle.VERTICAL_CENTER;
            cellStyle.BorderBottom = HSSFCellStyle.BORDER_THIN;
            cellStyle.BorderBottom = HSSFCellStyle.BORDER_THIN;
            cellStyle.BottomBorderColor = HSSFColor.BLACK.index;
            cellStyle.BorderLeft = HSSFCellStyle.BORDER_THIN;
            cellStyle.LeftBorderColor = HSSFColor.BLACK.index;
            cellStyle.BorderRight = HSSFCellStyle.BORDER_THIN;
            cellStyle.RightBorderColor = HSSFColor.BLACK.index;
            cellStyle.BorderTop = HSSFCellStyle.BORDER_THIN;
            cellStyle.TopBorderColor = HSSFColor.BLACK.index;

            var index = 0;
            foreach (var dt in set)
            {
                index++;
                var hssfSheet =
                    hssfworkbook.CreateSheet(string.IsNullOrEmpty(dt.TableName) ? "Sheet" + index : dt.TableName);

                #region 表头

                hssfSheet.DefaultColumnWidth = 20;
                hssfSheet.SetColumnWidth(0, 35 * 256);
                hssfSheet.SetColumnWidth(3, 20 * 256);
                // 表头
                var tagRow = hssfSheet.CreateRow(0);
                tagRow.Height = 22 * 20;

                int colIndex;
                for (colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
                {
                    tagRow.CreateCell(colIndex).SetCellValue(dt.Columns[colIndex].ColumnName);
                    tagRow.GetCell(colIndex).CellStyle = cellStyle;
                }

                #endregion

                #region 表数据

                // 表数据 
                for (var k = 0; k < dt.Rows.Count; k++)
                {
                    var dr = dt.Rows[k];
                    var row = hssfSheet.CreateRow(k + 1);
                    for (var i = 0; i < dt.Columns.Count; i++)
                    {
                        row.CreateCell(i).SetCellValue(dr[i].ToString());
                        row.GetCell(i).CellStyle = cellStyle;
                    }
                }

                #endregion
            }

            var path = HttpContext.Current.Server.MapPath("~/UploadFiles/Export");
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            using (var file = new FileStream(Path.Combine(path, fileName), FileMode.Create))
            {
                hssfworkbook.Write(file);
                file.Close();
            }

            return string.Format("{0}UploadFiles/Export/{1}", BasePath, fileName);
        }

        /// <summary>
        ///     将DataSet导出到Excel,返回文件的web路径
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static string ExportDataTableToExcel(DataSet set, string fileName)
        {
            var hssfworkbook = new HSSFWorkbook();

            // 标题样式
            var cellStyle = hssfworkbook.CreateCellStyle();
            cellStyle.Alignment = HSSFCellStyle.ALIGN_CENTER;
            cellStyle.VerticalAlignment = HSSFCellStyle.VERTICAL_CENTER;
            cellStyle.BorderBottom = HSSFCellStyle.BORDER_THIN;
            cellStyle.BorderBottom = HSSFCellStyle.BORDER_THIN;
            cellStyle.BottomBorderColor = HSSFColor.BLACK.index;
            cellStyle.BorderLeft = HSSFCellStyle.BORDER_THIN;
            cellStyle.LeftBorderColor = HSSFColor.BLACK.index;
            cellStyle.BorderRight = HSSFCellStyle.BORDER_THIN;
            cellStyle.RightBorderColor = HSSFColor.BLACK.index;
            cellStyle.BorderTop = HSSFCellStyle.BORDER_THIN;
            cellStyle.TopBorderColor = HSSFColor.BLACK.index;

            var index = 0;
            foreach (DataTable dt in set.Tables)
            {
                index++;
                var hssfSheet =
                    hssfworkbook.CreateSheet(string.IsNullOrEmpty(dt.TableName) ? "Sheet" + index : dt.TableName);

                #region 表头

                hssfSheet.DefaultColumnWidth = 20;
                hssfSheet.SetColumnWidth(0, 35 * 256);
                hssfSheet.SetColumnWidth(3, 20 * 256);
                // 表头
                var tagRow = hssfSheet.CreateRow(0);
                tagRow.Height = 22 * 20;

                int colIndex;
                for (colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
                {
                    tagRow.CreateCell(colIndex).SetCellValue(dt.Columns[colIndex].ColumnName);
                    tagRow.GetCell(colIndex).CellStyle = cellStyle;
                }

                #endregion

                #region 表数据

                // 表数据 
                for (var k = 0; k < dt.Rows.Count; k++)
                {
                    var dr = dt.Rows[k];
                    var row = hssfSheet.CreateRow(k + 1);
                    for (var i = 0; i < dt.Columns.Count; i++)
                    {
                        row.CreateCell(i).SetCellValue(dr[i].ToString());
                        row.GetCell(i).CellStyle = cellStyle;
                    }
                }

                #endregion
            }

            var path = HttpContext.Current.Server.MapPath("~/UploadFiles/Export");
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            using (var file = new FileStream(Path.Combine(path, fileName), FileMode.Create))
            {
                hssfworkbook.Write(file);
                file.Close();
            }

            return string.Format("{0}UploadFiles/Export/{1}", BasePath, fileName);
        }

        /// <summary>
        ///     将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns>返回的DataTable</returns>
        public static DataTable ExcelToDataTable(string fileName)
        {
            var data = new DataTable();
            try
            {
                var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                var workbook = new HSSFWorkbook(fileStream);
                var sheet = workbook.GetSheetAt(0);

                if (sheet != null)
                {
                    var firstRow = sheet.GetRow(0);
                    var cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    for (var i = firstRow.FirstCellNum; i < cellCount; ++i)
                    {
                        var cell = firstRow.GetCell(i);
                        if (cell != null)
                        {
                            var cellValue = cell.StringCellValue;
                            if (cellValue != null)
                            {
                                var column = new DataColumn(cellValue);
                                data.Columns.Add(column);
                            }
                        }
                    }

                    var startRow = sheet.FirstRowNum + 1;

                    //最后一列的标号
                    var rowCount = sheet.LastRowNum;
                    for (var i = startRow; i <= rowCount; ++i)
                    {
                        var row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null       

                        var dataRow = data.NewRow();
                        for (var j = row.FirstCellNum; j < cellCount; ++j)
                            if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                                dataRow[j] = row.GetCell(j).ToString();
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}
        

如果觉得文章对您有帮助,您可以对我进行打赏 ¥1.66 元(金额随机^_^,每次刷新金额不同)。

请使用支付宝扫码支付

留言评论

*称  呼:
*联系方式: 方便与您取得联系,推荐使用邮箱。
*内  容:

已有评论

暂无数据

上一篇:C# DES对称加密(需自行配置秘钥)

下一篇:C# Zip压缩包辅助类(需下载ICSharpCode组件,见代码顶部注释)