读取Excel数据问题

读取Excel数据进行操作,在本地运行正常,但部署到服务器后却读取不到Excel文件的数据,本来以为是没有把Excel上传到服务器而是直接读取Excel的问题,但是改为上传到服务器再读取还是无法解决问题,代码如下:

HttpPostedFile upFile = up_file.PostedFile;//HttpPostedFile对象,用来读取上传控件的属性
fileLength = upFile.ContentLength;//记录文件的长度
string FilePath = "";
try
{
    if (fileLength == 0)//当文件长度为0的时候
    {
        msg("请选择正确的文件");
    }
    else
    {
        string extName = upFile.FileName.Substring(upFile.FileName.LastIndexOf('.') + 1);
        if (extName != "xls" && extName != "xlsx")
        {
            msg("请选择正确的文件");
            return;
        }
        string strpath = upFile.FileName.ToString();   //获取Execle文件路径
        string filename = "Sheet1"; //指定Excel表名
        //获取随机文件名
        Random n = new Random();
        int randomn = n.Next(1000, 9999);
        FilePath = Server.MapPath("../zczx/files") + "/" + DateTime.Now.ToString("yyyyMMddhhmmss") + randomn.ToString() + "." + extName; ; 
        upFile.SaveAs(FilePath); //上传文件到指定目录

        //读取Excel数据
        //dtExcel = imp.ImportExcel(strpath, filename);  //原来的方法 直接读取本地上传的Excel数据
        dtExcel = ImportExcel(FilePath, filename);     

        if (dtExcel.Rows.Count == 0)
        {
            msg("Excel表无数据!");
        }
        else
        {
            //操作读取的Excel表数据
        }
    }
}
catch (Exception ex)
{
    msg(ex.Message);
}
finally
{
    System.IO.File.Delete(FilePath); //删除文件
}
读取Excel的方法:

public DataTable ImportExcel(string strImportFileName, string strImportSheetName)
{
    //string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strImportFileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
    string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strImportFileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1';"; //兼容2003&2007
    OleDbConnection connOle = new OleDbConnection(strConn);
    DataSet ds = new DataSet();
    try
    {
        connOle.Open();
        string strSql = string.Format("select * from [{0}$]", strImportSheetName);
        OleDbDataAdapter adp = new OleDbDataAdapter(strSql, connOle);
        adp.Fill(ds);
    }
    catch
    {
    }
    finally
    {
        connOle.Close();
        connOle.Dispose();
    }
 
    return ds.Tables[0];
}

最后发现是因为服务器没有装Excel程序。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值