zoukankan      html  css  js  c++  java
  • 封装Excel2007开源组件EPPlus——用于常规的导入导出

    EPPlus 是一款功能强大的开源OpenXml Excel组件,目前国内的资料还很少,最近为了替换以前闭源的Excel2007组件(因有一些bug无法修改),作了简单的封装,用于常规的导入导出。

    分享一下:

      1 using System;
      2 using System.Data;
      3 using System.IO;
      4 using System.Linq;
      5 using System.Text;
      6 using System.Web;
      7 using OfficeOpenXml;
      8 
      9 namespace CnSharp.IO.Excel
     10 {
     11     /// <summary>
     12     ///  Output <see cref="DataTable"/> to Excel2007 or above version that base on open xml formater
     13     /// </summary>
     14     public class OpenXmlExcelHelper
     15     {
     16         #region Constants and Fields
     17 
     18         public const int MaxSheetRows2007 = 1048576;
     19 
     20         #endregion
     21 
     22         #region Public Methods
     23 
     24         public static void Export(DataTable table, string fileName)
     25         {
     26             var rows = 0;
     27             Export(table, fileName, string.Empty, ref rows);
     28         }
     29 
     30         public static void Export(DataTable table, string fileName, string sheetName, ref int rowWrited)
     31         {
     32             if (table == null || table.Rows.Count == 0)
     33             {
     34                 return;
     35             }
     36             if (string.IsNullOrEmpty(sheetName))
     37             {
     38                 sheetName = "Sheet";
     39             }
     40             //if (table.Rows.Count > ExcelUtil.GetMaxRowSupported(fileName))
     41             //    throw new ArgumentException(string.Format("data rows cann't be more than {0}",
     42             //        ExcelUtil.GetMaxRowSupported(fileName)));
     43             var excel = new ExcelPackage(new FileInfo(fileName));
     44             using (excel)
     45             {
     46                 WriteSheets(table, excel, sheetName);
     47                 excel.Save();
     48             }
     49         }
     50 
     51 
     52         public static void ExportByWeb(DataTable table, string fileName, string sheetName)
     53         {
     54             using (var excel = new ExcelPackage())
     55             {
     56                 WriteSheets(table, excel, sheetName);
     57                 var context = HttpContext.Current;
     58                 context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
     59                 context.Response.ContentEncoding = Encoding.UTF8;
     60                 context.Response.Charset = "";
     61                 context.Response.AppendHeader(
     62                     "Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
     63                 context.Response.BinaryWrite(excel.GetAsByteArray());
     64                 context.Response.Flush();
     65                 context.Response.End();
     66             }
     67         }
     68 
     69 
     70         public static DataTable Import(string fileName)
     71         {
     72             var dt = new DataTable();
     73             using (var excel = new ExcelPackage(new FileInfo(fileName)))
     74             {
     75                 var sheet = excel.Workbook.Worksheets.First();
     76                 if (sheet == null)
     77                 {
     78                     return null;
     79                 }
     80                 foreach (var cell in sheet.Cells[1, 1, 1, sheet.Dimension.End.Column])
     81                 {
     82                     dt.Columns.Add(cell.Value.ToString());
     83                 }
     84                 var rows = sheet.Dimension.End.Row;
     85                 for (var i = 1; i <= rows; i++)
     86                 {
     87                     var row = sheet.Cells[i, 1, i, sheet.Dimension.End.Column];
     88                     dt.Rows.Add(row.Select(cell => cell.Value).ToArray());
     89                 }
     90                 return dt;
     91             }
     92         }
     93 
     94         
     95         private  static void FormatCell(ExcelRangeBase cell,DataColumn column)
     96         {
     97             //if (column.DataType == typeof(DateTime))
     98             //{
     99             //    cell.Style.Numberformat.Format = System.Globalization.DateTimeFormatInfo.CurrentInfo.LongDatePattern;
    100             //    return;
    101             //}
    102             //if (column.DataType.IsValueType) // == typeof(Decimal) || column.DataType == typeof(Double) || column.DataType == typeof(Single))
    103             //{
    104             //    cell.Style.Numberformat.Format = "#,##0.00";
    105             //}
    106         }
    107 
    108         #endregion
    109 
    110         #region Methods
    111 
    112         private static ExcelWorksheet CreateSheet(ExcelPackage excel, string sheetName)
    113         {
    114             foreach (var sheet in excel.Workbook.Worksheets)
    115             {
    116                 if (String.Compare(sheet.Name, sheetName, StringComparison.OrdinalIgnoreCase) == 0)
    117                 {
    118                     return sheet;
    119                 }
    120             }
    121             return excel.Workbook.Worksheets.Add(sheetName);
    122         }
    123 
    124 
    125         private static void WriteSheet(DataTable table, ExcelPackage excel, string sheetName, int startRowIndex,
    126                                        int endRowIndex)
    127         {
    128             var sheet = CreateSheet(excel, sheetName);
    129             var i = 1;
    130             foreach (DataColumn col in table.Columns)
    131             {
    132                 FormatCell(sheet.Cells[1, i],col);
    133                 sheet.Cells[1, i].Value = col.ColumnName;
    134                 i++;
    135             }
    136             var columnCount = table.Columns.Count;
    137             i = 2;
    138             for (var m = startRowIndex; m <= endRowIndex; m++)
    139             {
    140                 var row = table.Rows[m];
    141                 for (var j = 1; j <= columnCount; j++)
    142                 {
    143                     FormatCell(sheet.Cells[i, j], table.Columns[j -1 ]);
    144                     sheet.Cells[i, j].Value = row[j - 1].ToString();
    145                 }
    146                 i++;
    147             }
    148         }
    149 
    150         //private static void WriteSheet(DataTable table, ExcelPackage excel, string sheetName)
    151         //{
    152         //    var sheet = CreateSheet(excel, sheetName);
    153         //    var i = 1;
    154         //    foreach (DataColumn col in table.Columns)
    155         //    {
    156         //        sheet.Cells[1, i].Value = col.ColumnName;
    157         //        i++;
    158         //    }
    159         //    var columnCount = table.Columns.Count;
    160         //    var rows = table.Rows.Count;
    161         //    for (i = 2 ; i <= rows; i++)
    162         //    {
    163         //        var row = table.Rows[i];
    164         //        for (var j = 1; j <= columnCount; j++)
    165         //        {
    166         //            sheet.Cells[i, j].Value = row[j - 1].ToString();
    167         //        }
    168         //    }
    169         //}
    170 
    171         private static void WriteSheets(DataTable table, ExcelPackage excel, string sheetName)
    172         {
    173                 const int max = MaxSheetRows2007 - 1;
    174                 var rows = table.Rows.Count;
    175                 var sheetCount = (rows%max == 0) ? rows/max : rows/max + 1;
    176                 for (var sheetNo = 0; sheetNo < sheetCount; sheetNo++)
    177                 {
    178                     WriteSheet(
    179                         table,
    180                         excel,
    181                         (sheetNo == 0) ? sheetName : sheetName + "_" + sheetNo,
    182                         sheetNo*max,
    183                         (sheetNo + 1)*max < rows ? (sheetNo + 1)*max - 1 : rows - 1
    184                         );
    185                 }
    186                 //WriteSheet(table, sheetIndex, ref rowWrited);
    187         }
    188 
    189         #endregion
    190     }
    191 }
    作者:CnSharp.com
    本文版权归CnSharp.com和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
  • 相关阅读:
    Qt单元测试工具 QTestlib(QVERIFY, QFETCH, QCOMPARE等)
    再续FPGA初心,京微齐力脱胎京微雅格重新起航(700万元天使轮,泰有基金领投,水木基金、臻云创投、泰科源跟投。数千万元Pre-A轮融资,领投方为海康基金)
    为何放弃 C++ 的工作(开发慢,难度高。完全不适应互联网的快速迭代的思想)
    c++ try catch 问题(没有throw就会被删除,加上/EHa这样就不会被删除)
    西方教育骗局,终于明白精英和普通人的残酷差别!(该校流传着一个数字——4。即“4小时睡眠、4杯咖啡、GPA4.0”——要想获得满分为4分的成绩,每天只睡4个小时,困了就喝4大杯咖啡)
    分析Net 内存对象
    Dynamic Routing Based On Redis
    词云
    vim与sublime
    ASP.NET Core 2.0 源代码
  • 原文地址:https://www.cnblogs.com/cnsharp/p/2691413.html
Copyright © 2011-2022 走看看