asp.net 读取Excle 兼容2007

    //将指定excel文件中的数据转换成DataTable
    /// <summary>
    /// 将指定excel文件中的数据转换成DataTable对象,供应用程序进一步处理
    /// </summary>
    /// <param name="filepath">文件路径</param>
    /// <returns></returns>
    public static DataTable import(string filepath)
    {
        DataTable rs = new DataTable();
        bool canopen = false;
        // 数据连接  HDR=Yes;IMEX=1;
        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=False;" +
            "Data Source=" + filepath.ToString() + ";" +
            "Extended Properties='Excel 8.0;IMEX=1'");

        try//尝试数据连接是否可用
        {
            conn.Open();
            conn.Close();
            canopen = true;
        }
        catch { }

        if (canopen)
        {
            try//如果数据连接可以打开则尝试读入数据
            {
                OleDbCommand myoledbcommand = new OleDbCommand("select * from [sheet1$]", conn);
                OleDbDataAdapter mydata = new OleDbDataAdapter(myoledbcommand);
                mydata.Fill(rs);
                conn.Close();
            }
            catch//如果数据连接可以打开但是读入数据失败,则从文件中提取出工作表的名称,再读入数据
            { //获取文件的工作表名
                string sheetname = getsheetname(filepath);
                if (sheetname.Length > 0)
                {
                    OleDbCommand myoledbcommand = new OleDbCommand("select * from [" + sheetname + "$]", conn);
                    OleDbDataAdapter mydata = new OleDbDataAdapter(myoledbcommand);
                    mydata.Fill(rs);
                    conn.Close();
                }
            }
        }
        else
        { // 如果oledb不能连接,就读取文件到流 
            StreamReader tmpstream;//=File.OpenText(filepath);   
            tmpstream = new StreamReader(filepath, System.Text.Encoding.GetEncoding("gb2312"));
            string tmpstr = tmpstream.ReadToEnd();
            tmpstream.Close();
            // 过滤表中内容的html字符
            rs = getdatatablefromstring(tmpstr);
            tmpstr = "";
        }
        return rs;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值