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 }
posted on 2012-09-18 20:13  CnSharp Studio  阅读(2804)  评论(7编辑  收藏  举报