ExcelHelper 电子表格帮助类(导出表格4-1)

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Diagnostics;
  6 using System.IO;
  7 using NPOI.HSSF.UserModel;
  8 using NPOI.SS.UserModel;
  9 using NPOI.XSSF.UserModel;
 10 namespace StorageERP.Utility
 11 {
 12 
 13 
 14     /// <summary>
 15     /// 电子表格帮助类
 16     /// </summary>
 17     public class ExcelHelper : IDisposable
 18     {
 19         private string fileName = null; //文件名
 20         private IWorkbook workbook = null;
 21         private FileStream fs = null;
 22         private bool disposed;
 23 
 24         public ExcelHelper(string fileName)
 25         {
 26             this.fileName = fileName;
 27             disposed = false;
 28         }
 29 
 30         /// <summary>
 31         /// 将DataTable数据导入到excel中
 32         /// </summary>
 33         /// <param name="data">要导入的数据</param>
 34         /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
 35         /// <param name="sheetName">要导入的excel的sheet的名称</param>
 36         /// <returns>导入数据行数(包含列名那一行)</returns>
 37       
 38         #region 将DataTable数据导入到excel中
 39         public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
 40         {
 41             int i = 0;
 42             int j = 0;
 43             int count = 0;
 44             ISheet sheet = null;
 45 
 46             fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
 47             if (fileName.IndexOf(".xlsx") > 0) // 2007版本
 48                 workbook = new XSSFWorkbook();
 49             else if (fileName.IndexOf(".xls") > 0) // 2003版本
 50                 workbook = new HSSFWorkbook();
 51 
 52             try
 53             {
 54                 if (workbook != null)
 55                 {
 56                     sheet = workbook.CreateSheet(sheetName);
 57                 }
 58                 else
 59                 {
 60                     return -1;
 61                 }
 62 
 63                 if (isColumnWritten == true) //写入DataTable的列名
 64                 {
 65                     IRow row = sheet.CreateRow(0);
 66                     for (j = 0; j < data.Columns.Count; ++j)
 67                     {
 68                         row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
 69                     }
 70                     count = 1;
 71                 }
 72                 else
 73                 {
 74                     count = 0;
 75                 }
 76 
 77                 for (i = 0; i < data.Rows.Count; ++i)
 78                 {
 79                     IRow row = sheet.CreateRow(count);
 80                     for (j = 0; j < data.Columns.Count; ++j)
 81                     {
 82                         row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
 83                     }
 84                     ++count;
 85                 }
 86                 workbook.Write(fs); //写入到excel
 87                 return count;
 88             }
 89             catch (Exception ex)
 90             {
 91                 Console.WriteLine("Exception: " + ex.Message);
 92                 return -1;
 93             }
 94         }
 95         #endregion
 96 
 97         /// <summary>
 98         /// 将List数据导入到excel中
 99         /// </summary>
100         /// <param name="data">要导入的数据</param>
101         /// <param name="sheetName">要导入的excel的sheet的名称</param>
102         /// <returns>导入数据行数(包含列名那一行)</returns>
103 
104         #region 将List数据导入到excel中
105         public int ListToExcel<T>(List<T> data, string sheetName)
106         {
107 
108             ISheet sheet = null;
109 
110             fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
111             if (fileName.IndexOf(".xlsx") > 0) // 2007版本
112                 workbook = new XSSFWorkbook();
113             else if (fileName.IndexOf(".xls") > 0) // 2003版本
114                 workbook = new HSSFWorkbook();
115 
116             try
117             {
118                 if (workbook != null)
119                 {
120                     sheet = workbook.CreateSheet(sheetName);
121                 }
122                 else
123                 {
124                     return -1;
125                 }
126 
127                 PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
128                 IRow row0 = sheet.CreateRow(0);
129                 for (int i = 0; i < properties.Count; i++)
130                 {
131                     PropertyDescriptor property = properties[i];
132                     Debug.WriteLine(property.Name);
133                     row0.CreateCell(i).SetCellValue(property.Name);
134                 }
135 
136                 int count = 1;
137                 object[] values = new object[properties.Count];
138                 foreach (T item in data)
139                 {
140                     IRow row = sheet.CreateRow(count);
141                     for (int j = 0; j < values.Length; j++)
142                     {
143                         object obj = properties[j].GetValue(item);
144                         Debug.WriteLine(properties[j].GetValue(item));
145                         row.CreateCell(j).SetCellValue(obj == null ? "" : obj.ToString());
146 
147                     }
148                     ++count;
149                 }
150                 workbook.Write(fs); //写入到excel
151                 return count;
152             }
153             catch (Exception ex)
154             {
155                 Console.WriteLine("Exception: " + ex.Message);
156                 return -1;
157             }
158         }
159         #endregion
160 
161         /// <summary>
162         /// 将excel中的数据导入到DataTable中
163         /// </summary>
164         /// <param name="sheetName">excel工作薄sheet的名称</param>
165         /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
166         /// <returns>返回的DataTable</returns>
167 
168         #region 将excel中的数据导入到DataTable中
169         public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
170         {
171             ISheet sheet = null;
172             DataTable data = new DataTable();
173             int startRow = 0;
174             try
175             {
176                 fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
177                 if (fileName.IndexOf(".xlsx") > 0) // 2007版本
178                     workbook = new XSSFWorkbook(fs);
179                 else if (fileName.IndexOf(".xls") > 0) // 2003版本
180                     workbook = new HSSFWorkbook(fs);
181 
182                 if (sheetName != null)
183                 {
184                     sheet = workbook.GetSheet(sheetName);
185                     if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
186                     {
187                         sheet = workbook.GetSheetAt(0);
188                     }
189                 }
190                 else
191                 {
192                     sheet = workbook.GetSheetAt(0);
193                 }
194                 if (sheet != null)
195                 {
196                     IRow firstRow = sheet.GetRow(0);
197                     int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
198 
199                     if (isFirstRowColumn)
200                     {
201                         for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
202                         {
203                             ICell cell = firstRow.GetCell(i);
204                             if (cell != null)
205                             {
206                                 string cellValue = cell.StringCellValue;
207                                 if (cellValue != null)
208                                 {
209                                     DataColumn column = new DataColumn(cellValue);
210                                     data.Columns.Add(column);
211                                 }
212                             }
213                         }
214                         startRow = sheet.FirstRowNum + 1;
215                     }
216                     else
217                     {
218                         startRow = sheet.FirstRowNum;
219                     }
220 
221                     //最后一列的标号
222                     int rowCount = sheet.LastRowNum;
223                     for (int i = startRow; i <= rowCount; ++i)
224                     {
225                         IRow row = sheet.GetRow(i);
226                         if (row == null)
227                             break;
228                         //continue; //没有数据的行默认是null       
229 
230                         DataRow dataRow = data.NewRow();
231                         for (int j = row.FirstCellNum; j < cellCount; ++j)
232                         {
233                             if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
234                                 dataRow[j] = row.GetCell(j).ToString();
235                         }
236                         data.Rows.Add(dataRow);
237                     }
238                 }
239 
240                 return data;
241             }
242             catch (Exception ex)
243             {
244                 Console.WriteLine("Exception: " + ex.Message);
245                 //System.Windows.Forms.MessageBox.Show(ex.Message);
246                 return null;
247             }
248         } 
249         #endregion
250 
251         public void Dispose()
252         {
253             Dispose(true);
254             GC.SuppressFinalize(this);
255         }
256 
257         protected virtual void Dispose(bool disposing)
258         {
259             if (!this.disposed)
260             {
261                 if (disposing)
262                 {
263                     if (fs != null)
264                         fs.Close();
265                 }
266 
267                 fs = null;
268                 disposed = true;
269             }
270         }
271     }
272 }
View Code
原文地址:https://www.cnblogs.com/ABC-wangyuhan/p/14179884.html