VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Excel教程 >
  • C#导入导出Excel

Excel导入导出在项目运用中并不少见,传统的情况一般都是采用插件的形式走流程,像这种的网上一大把就不再复述。这里就写出完整的思路以及代码,供大家借鉴。

一、添加引用dotnet4(网上有,可以自行下载)

二、添加导入导出类Entities.cs

复制代码
  1 public class Entities:IDisposable
  2     {
  3         private string fileName = null; //文件名
  4         private static IWorkbook workbook = null;
  5         private static FileStream fs = null;
  6         private bool disposed;
  7 
  8         public Entities(string fileName)
  9         {
 10             this.fileName = fileName;
 11             disposed = false;
 12             
 13         }
 14 
 15         #region 将excel中的数据导入到DataTable中
 16         /// <summary>
 17         /// 将excel中的数据导入到DataTable中
 18         /// </summary>
 19         ///  <param name="fileNameurl">表名</param>
 20         /// <param name="sheetName">excel工作薄sheet的名称</param>
 21         /// <returns>返回的DataTable</returns>
 22         public static DataTable ExcelToDataTableHelper(string fileNameurl, string sheetName)
 23         {
 24             return ExcelToDataTableHelper(fileNameurl, sheetName, 1);
 25         }
 26 
 27         /// <summary>
 28         /// 将excel中的数据导入到DataTable中
 29         /// </summary>
 30         ///  <param name="fileNameurl">表名</param>
 31         /// <param name="sheetName">excel工作薄sheet的名称</param>
 32         /// <param name="ColumnNum">第几行是表头</param>
 33         /// <returns>返回的DataTable</returns>
 34         public static DataTable ExcelToDataTableHelper(string fileNameurl, string sheetName, int ColumnNum)
 35         {
 36             ISheet sheet = null;
 37             DataTable data = new DataTable();
 38             int startRow = 0;
 39             try
 40             {
 41                 fs = new FileStream(fileNameurl, FileMode.Open, FileAccess.Read);
 42                 if (fileNameurl.IndexOf(".xlsx") > 0) // 2007版本
 43                     workbook = new XSSFWorkbook(fs);
 44                 else if (fileNameurl.IndexOf(".xls") > 0) // 2003版本
 45                     workbook = new HSSFWorkbook(fs);
 46 
 47                 if (sheetName != null)
 48                 {
 49                     sheet = workbook.GetSheet(sheetName);
 50                     if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
 51                     {
 52                         sheet = workbook.GetSheetAt(0);
 53                     }
 54                 }
 55                 else
 56                 {
 57                     sheet = workbook.GetSheetAt(0);
 58                 }
 59                 if (sheet != null)
 60                 {
 61                     IRow firstRow;
 62 
 63                     // firstRow = sheet.GetRow(0);
 64                     if (ColumnNum > 0)
 65                     {
 66                         firstRow = sheet.GetRow(ColumnNum - 1);
 67                     }
 68                     else
 69                     {
 70                         firstRow = sheet.GetRow(0);
 71                     }
 72                     int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
 73 
 74                     for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
 75                     {
 76                         ICell cell = firstRow.GetCell(i);
 77                         if (cell != null)
 78                         {
 79                             string cellValue = cell.StringCellValue;
 80                             if (cellValue != null && cellValue != "")
 81                             {
 82                                 DataColumn column = new DataColumn(cellValue);
 83                                 data.Columns.Add(column);
 84                             }
 85                         }
 86                     }
 87                     cellCount = data.Columns.Count;
 88 
 89                     //找出第几行是列名
 90                     startRow = ColumnNum;
 91 
 92                     //startRow = firstDataNum-1;
 93                     //最后一列的标号
 94                     int rowCount = sheet.LastRowNum;
 95                     for (int i = startRow; i <= rowCount; ++i)
 96                     {
 97                         IRow row = sheet.GetRow(i);
 98                         if (row == null) continue; //没有数据的行默认是null       
 99                         DataRow dataRow = data.NewRow();
100                         for (int j = row.FirstCellNum; j < cellCount; ++j)
101                         {
102                             if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
103                             {
104                                 //dataRow[j] = row.GetCell(j).ToString();
105                                 //读取Excel格式,根据格式读取数据类型
106                                 ICell cell = row.GetCell(j);
107                                 dataRow[j] = parseExcel(cell);
108                             }
109                         }
110                         data.Rows.Add(dataRow);
111                     }
112                 }
113                 return data;
114             }
115             catch (Exception ex)
116             {
117                 Console.WriteLine("Exception: " + ex.Message);
118                 return null;
119             }
120             finally
121             {
122                 if (fs != null)
123                     fs.Close();
124             }
125         }
126 
127         //格式转换
128         private static String parseExcel(ICell cell)
129         {
130             string result = "";
131             switch (cell.CellType)
132             {
133                 case CellType.Formula:
134                     HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook);
135                     result = e.Evaluate(cell).StringValue;
136                     break;
137                 case CellType.Numeric:// 数字类型  
138                     if (HSSFDateUtil.IsCellDateFormatted(cell))
139                     {// 处理日期格式、时间格式  
140                         string sdf = "";
141                         if (cell.CellStyle.DataFormat == HSSFDataFormat
142                                 .GetBuiltinFormat("h:mm"))
143                         {
144                             sdf = "HH:mm";
145                         }
146                         else
147                         {// 日期  
148                             sdf = "yyyy-MM-dd";
149                         }
150                         DateTime date = cell.DateCellValue;
151                         result = date.ToString(sdf);
152                     }
153                     else if (cell.CellStyle.DataFormat == 58)
154                     {
155                         // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)  
156                         string sdf = "yyyy-MM-dd";
157                         double value = cell.NumericCellValue;
158                         DateTime date = new DateTime(1899, 12, 30); // 起始时间
159                         date = date.AddDays(value);
160                         result = date.ToString(sdf);
161                     }
162                     else
163                     {
164                         result = cell.NumericCellValue.ToString();
165                     }
166                     break;
167                 case CellType.String:// String类型  
168                     result = cell.StringCellValue;
169                     break;
170                 case CellType.Blank:
171                     result = "";
172                     break;
173                 default:
174                     result = "";
175                     break;
176             }
177             return result;
178         }
179 
180         /// <summary>
181         /// 获取Exce工作薄名称
182         /// </summary>
183         /// <param name="fileNameurl"></param>
184         /// <returns></returns>
185         public static List<string> GetSheetNames(string fileNameurl)
186         {
187             using (FileStream sr = new FileStream(fileNameurl, FileMode.OpenOrCreate))
188             {
189                 //根据路径通过已存在的excel来创建HSSFWorkbook,即整个excel文档
190                 HSSFWorkbook workbook = new HSSFWorkbook(sr);
191                 int x = workbook.Workbook.NumSheets;
192                 List<string> sheetNames = new List<string>();
193                 for (int i = 0; i < x; i++)
194                 {
195                     sheetNames.Add(workbook.Workbook.GetSheetName(i));
196                 }
197                 return sheetNames;
198             }
199         }
200 
201         //资源释放
202         public void Dispose()
203         {
204             //释放资源
205             Dispose(true);
206             //告诉垃圾回收器不要调用指定对象的Dispose方法
207             GC.SuppressFinalize(this);
208         }
209 
210         protected virtual void Dispose(bool disposing)
211         {
212             if (!this.disposed)
213             {
214                 if (disposing)
215                 {
216                     if (fs != null)
217                         fs.Close();
218                 }
219 
220                 fs = null;
221                 disposed = true;
222             }
223         }
224 #endregion
225     }
复制代码

将Entities类作为导入导出Excel的中枢

 

三、上传Excel模版

选好模版后将之放入文件夹,通过Upload方法实现模版下载

复制代码
 1  [HttpPost]
 2         public ActionResult Upload(HttpPostedFileBase file)
 3         {
 4             if (file == null)
 5             {
 6                 return Content("没有文件!", "text/plain");
 7             }
 8             var fileName = Path.Combine(Request.MapPath("~/Upload"), Path.GetFileName(file.FileName));
 9             //string strFilePaht = "~/Upload";
10             //string filename = Path.GetFileNameWithoutExtension(fileName); //这个就是获取文件名的
11             Session["filename"] = fileName;
12             try
13             {
14                 file.SaveAs(fileName);
15                 Response.Write("<script>alert('上传成功')</script>");
16             }
17             catch
18             {
19                 return Content("上传异常 !", "text/plain");
20             }
21             return View();
22         }
复制代码

这里只是一个简单的文件下载逻辑,后面有待完善

 

四、当下载好模版后将需要导入的Excel数据使用Import方法导入到DataTable,存入到数据库

复制代码
 1 public ActionResult Import()
 2         {
 3             //继承来自上传文件的文件路径 ,该路径为相对路径
 4             string pathName = Session["filename"].ToString();
 5             if (pathName=="")
 6             {
 7                 return Json("erro",JsonRequestBehavior.AllowGet);
 8             }
 9             string sheet = "Sheet1";
10             //传入参数,将excel转换为Datatable,格式文件名加上固定模版Sheet1
11             DataTable dt = Infotype.ExcelHelper.Entities.ExcelToDataTableHelper(pathName, sheet);
12             //循环这个集合并添加到数据表
13             int i = 0;
14             foreach (DataRow item in dt.Rows)
15             {
16                 tab.ProjectName = item[0].ToString();
17                 tab.InfoTypes = item[1].ToString();
18                 tab.field = item[2].ToString();
19                 tab.fieldtxt = item[3].ToString();
20                 db.InfoTables.Add(tab);
21                  i = db.SaveChanges();
22             }
23             if (i > 0)
24             {
25                 return Json("Data", JsonRequestBehavior.AllowGet);
26             }
27             else
28             {
29                 return Json("NOData", JsonRequestBehavior.AllowGet);
30             }
31 
32         }
复制代码

 

五、当修改了数据需要及时导出到Excel时就可以用到ExportStu2导出了

 

复制代码
 1 public FileResult ExportStu2()
 2         {
 3             //获取list数据
 4             var checkList = db.InfoTables.Where(r => r.ProjectName != null).Select(r => new { r.ProjectName,r.InfoTypes,r.field,r.fieldtxt }).ToList();
 5             //创建Excel文件的对象
 6             NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
 7             //添加一个sheet
 8             NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
 9 
10             //给sheet1添加第一行的头部标题
11             NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
12             row1.CreateCell(0).SetCellValue("项目名称");
13             row1.CreateCell(1).SetCellValue("信息类型");
14             row1.CreateCell(2).SetCellValue("字段");
15             row1.CreateCell(3).SetCellValue("字段名称");
16             //....N行
17 
18             //将数据逐步写入sheet1各个行
19             for (int i = 0; i < checkList.Count(); i++)
20             {
21                 NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
22                 rowtemp.CreateCell(0).SetCellValue(checkList[i].ProjectName.ToString());
23                 rowtemp.CreateCell(1).SetCellValue(checkList[i].InfoTypes.ToString());
24                 rowtemp.CreateCell(2).SetCellValue(checkList[i].field.ToString());
25                 rowtemp.CreateCell(3).SetCellValue(checkList[i].fieldtxt.ToString());
26                 //....N行
27             }
28             // 写入到客户端 
29             System.IO.MemoryStream ms = new System.IO.MemoryStream();
30             book.Write(ms);
31             ms.Seek(0, SeekOrigin.Begin);
32             DateTime dt = DateTime.Now;
33             string dateTime = dt.ToString("yyMMddHHmmssfff");
34             string fileName = "查询结果" + dateTime + ".xls";
35             return File(ms, "application/vnd.ms-excel", fileName);
36         }
复制代码

 

以上为我使用Excel导入导出的五大步骤,代码为示例,可根据实际情况使用

出处:https://www.cnblogs.com/taocheng/p/6957696.html
 


相关教程