NPOI库读写Excel文件

  1 //先用vs包管理器安装NPOI库
  2 
  3 public class ExcelUtility {
  4 
  5         /// <summary>
  6         /// DataSet数据导出到Excel文件
  7         /// </summary>
  8         /// <param name="ds">DataSet</param>
  9         /// <param name="fileName">文件全名</param>
 10         /// <returns></returns>
 11         public static bool DataSetToExcel(DataSet ds, string fileName) {
 12             IWorkbook workbook = new HSSFWorkbook();
 13             FileStream fs = null;
 14             try {
 15                 int k = 0;
 16                 foreach (DataTable dt in ds.Tables) {
 17                     if (dt != null && dt.Rows.Count > 0) {
 18                         ISheet sheet = null;
 19                         if (!string.IsNullOrWhiteSpace(dt.TableName)) {
 20                             sheet = workbook.CreateSheet(dt.TableName);//创建一个名称为Sheet0的表
 21                         }
 22                         else {
 23                             sheet = workbook.CreateSheet("Sheet" + k.ToString());//创建一个名称为Sheet0的表
 24                         }
 25                         int rowCount = dt.Rows.Count;//行数  
 26                         int columnCount = dt.Columns.Count;//列数
 27 
 28                         //设置列头  
 29                         IRow row = sheet.CreateRow(0);//excel第一行设为列头
 30                         ICell cell = null;
 31                         for (int c = 0; c < columnCount; c++) {
 32                             cell = row.CreateCell(c);
 33                             cell.SetCellValue(dt.Columns[c].ColumnName);
 34                         }
 35 
 36                         //设置每行每列的单元格,  
 37                         for (int i = 0; i < rowCount; i++) {
 38                             row = sheet.CreateRow(i + 1);
 39                             for (int j = 0; j < columnCount; j++) {
 40                                 cell = row.CreateCell(j);//excel第二行开始写入数据  
 41                                 cell.SetCellValue(dt.Rows[i][j].ToString());
 42                             }
 43                         }
 44                         //设置最后一列单元格宽度
 45                         sheet.SetColumnWidth(columnCount - 1,20000);
 46                         k = k + 1;
 47                     }
 48                 }
 49                 using (fs = File.OpenWrite(fileName)) {
 50                     workbook.Write(fs);//向打开的这个xls文件中写入数据  
 51                 }
 52                 return true;
 53             }
 54             catch (Exception ex) {
 55                 if (fs != null) {
 56                     fs.Close();
 57                 }
 58                 return false;
 59             }
 60         }
 61 
 62         /// <summary>
 63         /// 将excel导入到dataset
 64         /// </summary>
 65         /// <param name="filePath">excel路径</param>
 66         /// <param name="isColumnName">第一行是否是列名</param>
 67         /// <returns>返回datatable</returns>
 68         public static DataSet ExcelToDataSet(string filePath, bool isColumnName) {
 69             DataSet dataset=new DataSet();
 70             DataTable dataTable = null;
 71             FileStream fs = null;
 72             IWorkbook workbook = null;
 73             int startRow = 0;
 74             try {
 75                 using (fs = File.OpenRead(filePath)) {
 76                     // 2007版本
 77                     if (filePath.IndexOf(".xlsx") > 0)
 78                         workbook = new XSSFWorkbook(fs);
 79                     // 2003版本
 80                     else if (filePath.IndexOf(".xls") > 0)
 81                         workbook = new HSSFWorkbook(fs);
 82                     
 83                     if (workbook != null) {
 84                         for (int n = 0; n < workbook.NumberOfSheets; n++) {
 85                             ISheet sheet = workbook.GetSheetAt(n); //读取第一个sheet,当然也可以循环读取每个sheet
 86                             dataTable = new DataTable();
 87                             if (sheet != null && sheet.SheetName!="") {
 88                                 dataTable.TableName = sheet.SheetName;
 89                                 int rowCount = sheet.LastRowNum; //总行数
 90                                 if (rowCount > 0) {
 91                                     IRow firstRow = sheet.GetRow(0); //第一行
 92                                     int cellCount = firstRow.LastCellNum; //列数
 93 
 94                                     //构建datatable的列
 95                                     DataColumn column = null;
 96                                     ICell cell = null;
 97                                     if (isColumnName) {
 98                                         startRow = 1; //如果第一行是列名,则从第二行开始读取
 99                                         for (int i = firstRow.FirstCellNum; i < cellCount; ++i) {
100                                             cell = firstRow.GetCell(i);
101                                             if (cell != null) {
102                                                 if (cell.StringCellValue != null) {
103                                                     column = new DataColumn(cell.StringCellValue);
104                                                     dataTable.Columns.Add(column);
105                                                 }
106                                             }
107                                         }
108                                     }
109                                     else {
110                                         for (int i = firstRow.FirstCellNum; i < cellCount; ++i) {
111                                             column = new DataColumn("column" + (i + 1));
112                                             dataTable.Columns.Add(column);
113                                         }
114                                     }
115 
116                                     //填充行
117                                     for (int i = startRow; i <= rowCount; ++i) {
118                                         IRow row = sheet.GetRow(i);
119                                         if (row == null || string.IsNullOrWhiteSpace(row.Cells[0].ToString()))
120                                             continue;
121 
122                                         DataRow dataRow = dataTable.NewRow();
123                                         for (int j = row.FirstCellNum; j < cellCount; ++j) {
124                                             cell = row.GetCell(j);
125                                             if (cell == null) {
126                                                 dataRow[j] = "";
127                                             }
128                                             else {
129                                                 //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
130                                                 switch (cell.CellType) {
131                                                     case CellType.Blank:
132                                                         dataRow[j] = "";
133                                                         break;
134                                                     case CellType.Numeric:
135                                                         short format = cell.CellStyle.DataFormat;
136                                                         //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
137                                                         if (format == 14 || format == 31 || format == 57
138                                                             || format == 58)
139                                                             dataRow[j] = cell.DateCellValue;
140                                                         else
141                                                             dataRow[j] = cell.NumericCellValue;
142                                                         break;
143                                                     case CellType.String:
144                                                         dataRow[j] = cell.StringCellValue;
145                                                         break;
146                                                 }
147                                             }
148                                         }
149                                         dataTable.Rows.Add(dataRow);
150                                     }
151                                 }
152                             }
153                             dataset.Tables.Add(dataTable);
154                         }
155                     }
156                 }
157                 return dataset;
158             }
159             catch (Exception) {
160                 if (fs != null) {
161                     fs.Close();
162                 }
163                 return null;
164             }
165         }
166 
167     }

猜你喜欢

转载自www.cnblogs.com/kerwincui/p/9124930.html