Excel编程篇之多个excel表导入到Dataset

 public class ExcelToDataset
{
    /// <summary>
    /// 导入Excel
    /// </summary>
    /// <param name="filePath"></param>
    /// <param name="dsSet"></param>
    /// <returns></returns>
    public static DataSet Excelreader(string filePath)
    {

        DataSet ds = new DataSet();
        string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + filePath;
        OleDbConnection myConn = new OleDbConnection(strCon);

        string strCom = GetExcelFirstTableName(filePath);
        myConn.Open();
        OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
        myCommand.Fill(ds);
        myConn.Close();
        return ds;
    }

    /// <summary>
    /// 返回Excel数据源
    /// </summary>
    /// <param name="filePath">文件路径</param>
    /// <param name="dsSet">数据集</param>
    /// <returns>DataSet</returns>
    public static DataSet InSertAnotherExcelToDataset(string filePath, DataSet dsSet)
    {
        DataSet ds=dsSet;
        string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;data source=" + filePath;
        OleDbConnection myConn = new OleDbConnection(strCon);

        string strCom = GetExcelFirstTableName(filePath);
        myConn.Open();
        OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
        myCommand.Fill(ds);
        myConn.Close();
        return ds;
    }
    /// <summary>
    /// 动态取Excel表名
    /// </summary>
    /// <param name="fullPath">文件路径</param>
    /// <returns></returns>
    public static string GetExcelFirstTableName(string fullPath)
    {
        string tableName = null;
        if (File.Exists(fullPath))
        {
            using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet." +
            "OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + fullPath))
            {
                conn.Open();
                var oleDbSchemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (oleDbSchemaTable != null)
                    tableName = oleDbSchemaTable.Rows[0][2].ToString().Trim();
            }
        }
        tableName="SELECT  * FROM [" + tableName + "]";
        return tableName;
    }

}

注意分析逻辑,遇到问题再仔细分析,切忌浮躁~相信前辈的Blog~

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值