任何人告诉我如何使用按钮单击上传ASP

任何人告诉我如何使用按钮单击上传ASP

本文介绍了任何人告诉我如何使用按钮单击上传ASP.NET(网格视图)中的Excel工作表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();
    string filename = string.Empty;
    if (FileUploadToServer.HasFile)
    {
        try
        {
            string[] allowdFile = { ".xls", ".xlsx" };
            string FileExt = System.IO.Path.GetExtension(FileUploadToServer.PostedFile.FileName);
            bool isValidFile = allowdFile.Contains(FileExt);
            if (!isValidFile)
            {
                lblMsg.ForeColor = System.Drawing.Color.Red;
                lblMsg.Text = "Please upload only Excel";
            }
            else
            {
                int FileSize = FileUploadToServer.PostedFile.ContentLength;
                if (FileSize <= 1048576)
                {
                    filename = Path.GetFileName(Server.MapPath(FileUploadToServer.FileName));

                    FileUploadToServer.SaveAs(Server.MapPath(FilePath) + filename);
                    string filePath = Server.MapPath(FilePath) + filename;
                    OleDbConnection con = null;
                    if (FileExt == ".xls")
                    {
                        con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0;");

                    }
                    else if (FileExt == ".xlsx")
                    {
                        con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;");
                    }
                    con.Open();
                    DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                    string getExcelSheetName = dt.Rows[0]["Table_Name"].ToString();
                    OleDbCommand ExcelCommand = new OleDbCommand(@"SELECT * FROM [" + getExcelSheetName + @"]", con);
                    OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
                    DataSet ExcelDataSet = new DataSet();
                    ExcelAdapter.Fill(ExcelDataSet);
                    con.Close();

                    GridView1.DataSource = ExcelDataSet;
                    GridView1.DataBind();
                }
                else
                {
                    lblMsg.Text = "Attachment file size should not be greater then 1 MB!";
                }
            }
        }
        catch (Exception ex)
        {
            lblMsg.Text = "Error occurred while uploading a file: " + ex.Message;
        }
    }
    else
    {
        lblMsg.Text = "Please select a file to upload.";
    }
}





我尝试了什么:



我不想要这个代码。给我Amny简单Codes.Becoz我不擅长程序



What I have tried:

I dont want this code.Give me Amny simple Codes.Becoz i am not good in programs

推荐答案


这篇关于任何人告诉我如何使用按钮单击上传ASP.NET(网格视图)中的Excel工作表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 03:12