由于工作原因,最近对EXCEL文件的操作和数据导入导出进行了学习。并把其中的一些常用方法总结出来,不敢私藏现在分享给大家。不足之处,还请指正。

(一)获取EXCEL文件SHEET的名称

方法1:

View Code
 1         public static string[] ExcelTableNames(string FileName)
2 {
3 string strXls = FileName.Substring(FileName.LastIndexOf(".")).ToLower();
4 string sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName + ";Extended Properties=Excel 8.0";
5 string[] ss = "";
6 string temp = "'$";
7 using (OleDbConnection oleConn = new OleDbConnection())
8 {
9 oleConn.ConnectionString = sConn;
10 try
11 {
12 oleConn.Open();
13 DataTable table = oleConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
14 if (table == null || table.Rows.Count == 0) return ss;
15 ss = new string[table.Rows.Count];
16 for (int i = 0; i < table.Rows.Count; ++i)
17 {
18 ss[i] = table.Rows[i]["Table_Name"].ToString();
19 // 由于如何sheet名称为中文字符,在获取如何shee和名称时会有$ '字符,所以使用了字符过滤。有好的方法还请指正。
20 ss[i] = ss[i].Trim(temp.ToCharArray());
21 }
22
23 }
24 catch(Exception e)
25 {
26 MessageBox.Show(e.ToString());
27 return ss;
28 }
29 finally
30 {
31 oleConn.Close();
32 }
33 }
34 return ss;
35 }

方法2:

View Code
 1         public static string[] GetTableNames(string FileName)
2 {
3 Microsoft.Office.Interop.Excel.ApplicationClass objExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
4 string[] strArray = null;
5 List<string> list = new List<string>();
6 try
7 {
8 Microsoft.Office.Interop.Excel.Workbook objWorkBook = objExcel.Workbooks.Open(FileName, Type.Missing,
9 Type.Missing, Type.Missing,
10 Type.Missing,
11 Type.Missing, Type.Missing,
12 Type.Missing, Type.Missing,
13 Type.Missing,
14 Type.Missing, Type.Missing,
15 Type.Missing, Type.Missing,
16 Type.Missing);
17 foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in objWorkBook.Sheets)
18 {
19 string str = sheet.Name.ToLower();
20 list.Add(str);
21 }
22 objWorkBook.Close(false, Type.Missing, Type.Missing);
23 objExcel.Quit();
24
25 strArray = new string[list.Count];
26 for (int i = 0; i < list.Count; i++)
27 {
28 strArray[i] = list[i];
29 }
30 return strArray;
31 }
32 catch (Exception e)
33 {
34 MessageBox.Show(e.ToString());
35 return strArray;
36 }
37 }

两种方法经过比较,由于方法2需要加载EXCEL的COM组件然后进行对文件进行操作方法1能够快速得到SHEET名称。

谢谢

作者: Aland.liu 发表于 2011-07-21 12:30 原文链接

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架
新浪微博粉丝精灵,刷粉丝、刷评论、刷转发、企业商家微博营销必备工具"