友情链接:.NET项目开发者博客

Excel操作表格

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Data;
 6 using System.Data.OleDb;
 7 using System.IO;
 8 
 9 namespace ExcelRead
10 {
11    public static class ExcelOperate
12     {
13        /// <summary>
14        /// 根据表格名称获取Excel中表格
15        /// </summary>
16        /// <param name="path"></param>
17        /// <param name="sheetName"></param>
18        /// <returns></returns>
19        public static DataTable GetTableFromExcel(string path, string sheetName)
20        {
21            // Path.GetExtension(path) == "xlsx" ? "Provider=Microsoft.Ace.OleDb.12.0;" :
22            string parame = "Provider=Microsoft.Jet.OleDb.4.0;";
23            string strConn = string.Format("{0}Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'", parame);
24            OleDbConnection OleConn = new OleDbConnection(strConn);
25            OleConn.Open();
26            String sql = string.Format("SELECT * FROM  [{0}$]", sheetName);
27 
28            OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
29            DataSet OleDsExcle = new DataSet();
30            OleDaExcel.Fill(OleDsExcle, sheetName);
31            OleConn.Close();
32 
33            DataTable table = OleDsExcle.Tables[0];
34            return table;
35        }
36        /// <summary>
37        /// 获取Excel中所有的表格名称
38        /// </summary>
39        /// <param name="path"></param>
40        /// <returns></returns>
41        public static List<String> GetSheetNameFromExcel(string path)
42        {
43            // Path.GetExtension(path) == ".xlsx" ? "Provider=Microsoft.Ace.OleDb.12.0;" : 
44            List<String> names = new List<string>();
45            string parame ="Provider=Microsoft.Jet.OleDb.4.0;";
46            string strConn = string.Format("{0}Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'", parame);
47 
48            OleDbConnection conn = new OleDbConnection(strConn);
49            conn.Open();
50            DataTable sheetNames = conn.GetOleDbSchemaTable
51            (OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
52            conn.Close();
53 
54            foreach (DataRow dr in sheetNames.Rows)
55            {
56                string sheetName = dr[2].ToString().Replace("'", "").Replace("'", "").Replace("$", "");
57                names.Add(sheetName.Trim());
58            }
59            return names;
60        }
61 
62     }
63 }

 

posted @ 2013-06-27 16:54  千年老妖  Views(228)  Comments(0)    收藏  举报
友情链接:.NET项目开发者博客