C#中读取EXCEL内容

using  System;
using  System.Collections.Generic;
using  System.Text;
using  System.Data;
using  System.Data.OleDb;

namespace  pro
{
   
public class MyExcel
    
{
                  
//连接字符串
            public const string Define_ConnectStringFormat = "Provider=Microsoft.Jet.OleDb.4.0;data source={0};Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
            
//SQL格式字符串
            public const string Define_SQLStringFormat = "Select   *   from   [{0}$]";
        
//Excel操作类
            private OleDbConnection conn = null;
            
private OleDbDataAdapter adapter = null;
      
            
/// <summary>
            
/// 打开Excel
            
/// </summary>
            
/// <param name="excelFilename">Excel名</param>
            
/// <returns>true:成功 false:失败</returns>
            
/// 

     
            
internal bool OpenExcel(string excelFilename)
            
{
                
try
                
{
                    
//生成连接字符串
                    string strConn = string.Format(MyExcel.Define_ConnectStringFormat, excelFilename);
                    conn 
= new OleDbConnection(strConn);
                    
return true;
                }

                
catch
                
{
                    
return false;
                }

            }


            
/// <summary>
            
///  取得Sheet的内容
            
/// </summary>
            
/// <param name="sheetName">Sheet名</param>
            
/// <returns>DataTable</returns>

            internal DataTable GetSheet(string sheetName)
            
{
                
try
                
{
                    
string strSQL = string.Format(MyExcel.Define_SQLStringFormat, sheetName);
                    adapter 
= new OleDbDataAdapter(strSQL, conn);
                    DataSet dataSet 
= new DataSet();
                    conn.Open();
                    adapter.Fill(dataSet, sheetName);
                    DataTable dataTable 
= dataSet.Tables[sheetName];
                    conn.Close();
                    
return dataTable;
                }

                
catch
                
{
                    
return null;
                }


            }

        

    }

}

 
调用:

使用命名空间:
using pro;

继承类:
protected MyExcel ex = new MyExcel();

打开excel文件:
ex.OpenExcel("book1.xls");

读取Excel内容:
DataTable dt1 = ex.GetSheet("sheet1");

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值