C#导入导出Excele数据

Posted 南山南

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#导入导出Excele数据相关的知识,希望对你有一定的参考价值。

注:对于实体类对象最好新建一个并且继承原有实体类,这样可以将类型进行修改;

方法一:此种方法是用EPPLUS中的FileInfo流进行读取的(是不是流我还真不太了解,若有懂得请留言,非常感谢了)

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using Abp.Extensions;
 7 
 8 namespace HYZT.Ltxy.International.Ctrip.Exporting
 9 {
10     public class ExcelLib
11     {
12         public  ICtripPolicyExcelImport GetExcel(string filePath)
13         {
14             if (filePath.Trim() .IsNullOrEmpty())
15                 throw new Exception("文件名不能为空");
16     //因为这儿用得是EPPLUS对Excel进行的操作,所以只能操作
17     //2007以后的版本以后的(即扩展名为.xlsx)
18             if (!filePath.Trim().EndsWith("xlsx"))
19                 throw new Exception("请使用office Excel 2007版本或2010版本");
20 
21             else if (filePath.Trim().EndsWith("xlsx"))
22             {
23                 ICtripPolicyExcelImport res = new CtripPolicyExcelImport(filePath.Trim());
24                 return res;
25             }
26             else return null;
27         }
28     }
29 }

方法接口:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace HYZT.Ltxy.International.Ctrip.Exporting
 8 {
 9     public interface ICtripPolicyExcelImport
10     {
11         /// <summary> 打开文件 </summary>  
12         bool Open();  
13         //ExcelVersion Version { get; }
14         /// <summary> 文件路径 </summary>  
15         string FilePath { get; set; }
16         /// <summary> 文件是否已经打开 </summary>  
17         bool IfOpen { get; }
18         /// <summary> 文件包含工作表的数量 </summary>  
19         int SheetCount { get; }
20         /// <summary> 当前工作表序号 </summary>  
21         int CurrentSheetIndex { get; set; }
22         /// <summary> 获取当前工作表中行数 </summary>  
23         int GetRowCount();
24         /// <summary> 获取当前工作表中列数 </summary>  
25         int GetColumnCount();
26         /// <summary> 获取当前工作表中某一行中单元格的数量 </summary>  
27         /// <param name="Row">行序号</param>  
28         int GetCellCountInRow(int Row);
29         /// <summary> 获取当前工作表中某一单元格的值(按字符串返回) </summary>  
30         /// <param name="Row">行序号</param>  
31         /// <param name="Col">列序号</param>  
32         string GetCellValue(int Row, int Col);
33         /// <summary> 关闭文件 </summary>  
34         void Close();  
35     }
36 }

方法实现:

  1 using OfficeOpenXml;
  2 using System;
  3 using System.Collections.Generic;
  4 using System.IO;
  5 using System.Linq;
  6 using System.Text;
  7 using System.Threading.Tasks;
  8 
  9 namespace HYZT.Ltxy.International.Ctrip.Exporting
 10 {
 11     public class CtripPolicyExcelImport:ICtripPolicyExcelImport
 12     {
 13 
 14         public CtripPolicyExcelImport()  
 15         { }  
 16   
 17         public CtripPolicyExcelImport(string path)  
 18         { filePath = path; }
 19 
 20 
 21         private string filePath = "";
 22         private ExcelWorkbook book = null;
 23         private int sheetCount = 0;
 24         private bool ifOpen = false;
 25         private int currentSheetIndex = 0;
 26         private ExcelWorksheet currentSheet = null;
 27         private ExcelPackage ep = null;  
 28   
 29          public bool Open()  
 30         {  
 31             try  
 32             {  
 33                 ep = new ExcelPackage(new FileInfo(filePath));  
 34                   
 35                 if (ep == null) return false;  
 36                 book =ep.Workbook;  
 37                 sheetCount = book.Worksheets.Count;  
 38                 currentSheetIndex = 0;  
 39                 currentSheet = book.Worksheets[1];  
 40                 ifOpen = true;  
 41             }  
 42             catch (Exception ex)  
 43             {  
 44                 throw new Exception(ex.Message);  
 45             }  
 46             return true;  
 47         }  
 48   
 49         public void Close()  
 50         {  
 51             if (!ifOpen || ep == null) return;  
 52             ep.Dispose();  
 53         }  
 54   
 55         //public ExcelVersion Version  
 56         //{ get { return ExcelVersion.Excel07; } }  
 57   
 58         public string FilePath  
 59         {  
 60             get { return filePath; }  
 61             set { filePath = value; }  
 62         }  
 63   
 64         public bool IfOpen  
 65         { get { return ifOpen; } }  
 66   
 67         public int SheetCount  
 68         { get { return sheetCount; } }  
 69   
 70         public int CurrentSheetIndex  
 71         {  
 72             get  { return currentSheetIndex; }  
 73             set  
 74             {  
 75                 if (value != currentSheetIndex)  
 76                 {  
 77                     if (value >= sheetCount)  
 78                         throw new Exception("工作表序号超出范围");  
 79                     currentSheetIndex = value;  
 80                     currentSheet =book.Worksheets[currentSheetIndex+1];  
 81                 }  
 82             }  
 83         }  
 84   
 85         public int GetRowCount()  
 86         {  
 87             if (currentSheet == null) return 0;  
 88             return currentSheet.Dimension.End.Row;  
 89         }  
 90   
 91         public int GetColumnCount()  
 92         {  
 93             if (currentSheet == null) return 0;  
 94             return currentSheet.Dimension.End.Column;  
 95         }  
 96    
 97         public int GetCellCountInRow(int Row)  
 98         {  
 99             if (currentSheet == null) return 0;  
100             if (Row >= currentSheet.Dimension.End.Row) return 0;  
101             return currentSheet.Dimension.End.Column;  
102         }  
103     //根据行号和列号获取指定单元格的数据
104         public string GetCellValue(int Row, int Col)  
105         {  
106             if (currentSheet == null) return "";  
107             if (Row >= currentSheet.Dimension.End.Row || Col >= currentSheet.Dimension.End.Column) return "";  
108             object tmpO =currentSheet.GetValue(Row+1, Col+1);  
109             if (tmpO == null) return "";  
110             return tmpO.ToString();  
111         }          
112     }          
113 }
方法调用实现功能:

1
//用于程序是在本地,所以此时的路径是本地电脑的绝对路劲; 2 //当程序发布后此路径应该是服务器上的绝对路径,所以在此之前还要有 3 //一项功能是将本地文件上传到服务器上的指定位置,此时在获取路径即可 4 public string GetExcelToCtripPolicy(string filePath) 5 { 6 ExcelLib lib = new ExcelLib(); 7 if (filePath == null) 8 return new ReturnResult<bool>(false, "未找到相应文件"); 9 string str= tmp.GetCellValue(i, j); 10 return str; 11 }

 

 

方法二:将Excel表格转化成DataTable表,然后在对DataTable进行业务操作

 1 using Abp.Application.Services;
 2 using OfficeOpenXml;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Data;
 6 using System.IO;
 7 using System.Linq;
 8 using System.Text;
 9 using System.Threading.Tasks;
10 
11 namespace HYZT.Ltxy.International.Ctrip.GetExcelToDataTable
12 {
13     public class EPPlusHelperAppService:ApplicationService,IEPPlusHelperAppService
14     {
15         private   static string GetString(object obj)
16         {
17             try
18             {
19                 return obj.ToString();
20             }
21             catch (Exception ex)
22             {
23                 return "";
24             }
25         }
26 
27         /// <summary>
28         ///将指定的Excel的文件转换成DataTable (Excel的第一个sheet)
29         /// </summary>
30         /// <param name="fullFielPath">文件的绝对路径</param>
31         /// <returns></returns>
32         public DataTable WorksheetToTable(string filePath)
33         {
34             try
35             {
36                 FileInfo existingFile = new FileInfo(filePath);
37 
38                 ExcelPackage package = new ExcelPackage(existingFile);
39                 ExcelWorksheet worksheet = package.Workbook.Worksheets[1];//选定 指定页
40 
41                 return WorksheetToTable(worksheet);
42             }
43             catch (Exception)
44             {
45                 throw;
46             }
47         }
48 
49         /// <summary>
50         /// 将worksheet转成datatable
51         /// </summary>
52         /// <param name="worksheet">待处理的worksheet</param>
53         /// <returns>返回处理后的datatable</returns>
54         public  static  DataTable WorksheetToTable(ExcelWorksheet worksheet)
55         {
56             //获取worksheet的行数
57             int rows = worksheet.Dimension.End.Row;
58             //获取worksheet的列数
59             int cols = worksheet.Dimension.End.Column;
60 
61             DataTable dt = new DataTable(worksheet.Name);
62             DataRow dr = null;
63             for (int i = 1; i <= rows; i++)
64             {
65                 if (i > 1)
66                     dr = dt.Rows.Add();
67 
68                 for (int j = 1; j <= cols; j++)
69                 {
70                     //默认将第一行设置为datatable的标题
71                     if (i == 1)
72                         dt.Columns.Add(GetString(worksheet.Cells[i, j].Value));
73                     //剩下的写入datatable
74                     else
75                         dr[j - 1] = GetString(worksheet.Cells[i, j].Value);
76                 }
77             }
78             return dt;
79         }
80     }
81 }

之前我有一个程序用的是方法一进行Excel导入的,速度不是很快,后来我又用了第二种方法但是速度更慢了,到底这两种方法哪种快,请大虾指导,还是我用第二种方法的时候业务判断有问题,不得而知,

就请明白人知道我到底这两种方法哪种比较好些;

 

以上是关于C#导入导出Excele数据的主要内容,如果未能解决你的问题,请参考以下文章

如何通过C#代码导出数据库并在本地导入?

c# 导入导出excel表格式

C#导入导出excel的问题

c#操作excel导入导出时同时向用户表插入账户与密码

C#把查询出来的数据导出到Excel代码怎么写

c#使用NPOI进行Excel导入导出,附源码,vs2010