ExcelHelper(with template)

    public static class ExcelHelper {
        private static Dictionary<int, DataTable> _DataSource = new Dictionary<int, DataTable>();

        #region Create excel file

        public static string CreateExcel(string filePath, DataSet dataSet) {
            try {

                // Create file
                using (Stream fileStream = File.Create(filePath)) {
                    HSSFWorkbook book = null;

                    book = CreateExcelFromDataSet(dataSet);
                    // Save excel file to stream.
                    book.Write(fileStream);
                }
            } catch (Exception ex) {
                throw ex;
            }

            return filePath;
        }

        public static string CreateTemplateExcel(string filePath, DataSet dataSet, int startIndex, string templatePath) {
            try {

                // Create file
                using (Stream fileStream = File.Create(filePath)) {
                    HSSFWorkbook book = null;

                    // book = CreateExcelFromDataSet(dataSet);
                    book = CreateExcelWithTemplate(startIndex, dataSet, templatePath);
                    // Save excel file to stream.
                    book.Write(fileStream);
                }
            } catch (Exception ex) {
                throw ex;
            }

            return filePath;
        }

        #region Create excel from template

        private static HSSFWorkbook CreateExcelWithTemplate(int startRowIndex, DataSet dataSet, string templatePath) {
            HSSFWorkbook book = null;

            #region Create Workbook

            if (!File.Exists(templatePath)) {
                throw new FileNotFoundException("Can not found the template file :" + templatePath);
            }

            using (Stream templateStream = File.OpenRead(templatePath)) {
                book = new HSSFWorkbook(templateStream);
            }

            #endregion

            ISheet workSheet = book.GetSheetAt(0);

            DataTable data = dataSet.Tables[0];
            int columnCount = data.Columns.Count;

            #region Write Data

            foreach (DataRow dataRow in data.Rows) {
                IRow sheetRow = workSheet.GetRow(startRowIndex);
                if (sheetRow == null)
                    sheetRow = workSheet.CreateRow(startRowIndex);

                for (int i = 0; i < columnCount; i++) {
                    ICell sheetCell = sheetRow.GetCell(i);
                    if (sheetCell == null)
                        sheetCell = sheetRow.CreateCell(i);

                    object cellValue = dataRow[i];
                    Type dataType = cellValue.GetType();

                    if (dataType == typeof(double) || dataType == typeof(int) || dataType == typeof(decimal) || dataType == typeof(long) || dataType == typeof(float))
                        sheetCell.SetCellValue(Convert.ToDouble(cellValue));
                    else if (dataType == typeof(DateTime))
                        sheetCell.SetCellValue(Convert.ToDateTime(cellValue).ToString());
                    else if (dataType == typeof(bool))
                        sheetCell.SetCellValue(Convert.ToBoolean(cellValue));
                    else
                        sheetCell.SetCellValue(Convert.ToString(cellValue));
                }

                startRowIndex++;
                // 做多支持65536行
                if (startRowIndex > 65536) {
                    break;
                }
            }

            #endregion

            return book;
        }

        #endregion


        #region Create excel from data set

        private static HSSFWorkbook CreateExcelFromDataSet(DataSet dataSet) {
            // New Workbook
            HSSFWorkbook book = new HSSFWorkbook();

            foreach (DataTable data in dataSet.Tables) {
                int columnCount = data.Columns.Count;
                int rowCount = data.Rows.Count;

                ISheet excelSheet = book.CreateSheet();

                #region Write Header

                IRow headerRow = excelSheet.GetRow(0);
                if (headerRow == null)
                    headerRow = excelSheet.CreateRow(0);

                for (int c = 0; c < columnCount; c++) {
                    string columnName = data.Columns[c].ColumnName;
                    ICell headerCell = headerRow.GetCell(c);
                    if (headerCell == null)
                        headerCell = headerRow.CreateCell(c);

                    headerCell.SetCellValue(columnName);
                }

                #endregion

                #region Write Data

                // Excel 最多65536行(其中标题占一行)
                if (rowCount > 65535)
                    rowCount = 65535;

                for (int r = 0; r < rowCount; r++) {
                    DataRow tableRow = data.Rows[r];
                    IRow dataRow = excelSheet.GetRow(r + 1);
                    if (dataRow == null)
                        dataRow = excelSheet.CreateRow(r + 1);

                    // 输出列
                    for (int c = 0; c < columnCount; c++) {
                        ICell dataCell = dataRow.GetCell(c);
                        if (dataCell == null)
                            dataCell = dataRow.CreateCell(c);

                        //tableRow.SetCellBg(c, dataCell);
                        object cellValue = tableRow[c];

                        if (cellValue == null || cellValue == DBNull.Value)
                            continue;

                        Type dataType = cellValue.GetType();

                        if (dataType == typeof(double) || dataType == typeof(int) || dataType == typeof(decimal) || dataType == typeof(long) || dataType == typeof(float))
                            dataCell.SetCellValue(Convert.ToDouble(cellValue));
                        else if (dataType == typeof(DateTime))
                            dataCell.SetCellValue(Convert.ToDateTime(cellValue).ToString());
                        else if (dataType == typeof(bool))
                            dataCell.SetCellValue(Convert.ToBoolean(cellValue));
                        else
                            dataCell.SetCellValue(Convert.ToString(cellValue));
                    }
                }

                #endregion
            }

            return book;
        }

        #endregion

        #endregion

        public static DataTable ToDataTable<T>(this IEnumerable<T> list) {

            //创建属性的集合    
            List<PropertyInfo> pList = new List<PropertyInfo>();
            //获得反射的入口    

            Type type = typeof(T);
            DataTable dt = new DataTable();
            //把所有的public属性加入到集合 并添加DataTable的列    
            Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
            foreach (var item in list) {
                //创建一个DataRow实例    
                DataRow row = dt.NewRow();
                //给row 赋值    
                pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
                //加入到DataTable    
                dt.Rows.Add(row);
            }
            return dt;
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值