winfrom导入excel文件

  private DataSet xsldata()            //定义一个dataset并把excel数据读入dataset
        {
            dataGridView1.Rows.Clear();
            OpenFileDialog openFile = new OpenFileDialog();//打开文件对话框。
            openFile.Filter = ("Excel 文件(*.xls)|*.xls");//后缀名。
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                string filename = openFile.FileName;  //文件路径             
                string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;IMEX=1'";
      // string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1'";          
                OleDbConnection Conn = new OleDbConnection(strCon);                
                Conn.Open();
     //动态导入很多Excel表格的时候,他们的表名可能不一样,总不能每次都输入一次表名吧,其它不需要的只要用下面的方法就可以得到表名
            //string tableName = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0][2].ToString().Trim();
            string strCom = "SELECT * FROM [sheet1$]";
           // string strCom = "SELECT * FROM [" + tableName + "]";
                OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, Conn);
                DataSet ds = new DataSet();
                myCommand.Fill(ds, "[sheet1$]");
       //myCommand.Fill(ds, tableName);
                Conn.Close();
                Conn.Dispose();
                return ds;    //返回dataset
            }
            else
                return null;
        }
    
 //string tableName = string.Empty;
 //动态导入很多Excel表格的时候,他们的表名可能不一样,总不能每次都输入一次表名吧,其它不需要的只要用下面的方法就可以得到表名
 //tableName = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0][2].ToString().Trim();
    

特别注意

    Extended Properties='Excel 8.0;HDR=yes;IMEX=1'

     A: HDR ( HeaDer Row )设置
    若指定值为Yes,代表 Excel 档中的工作表第一行是栏位名称

    若指定值為 No,代表 Excel 档中的工作表第一行就是資料了,沒有栏位名称

    B:IMEX ( IMport EXport mode )设置

     IMEX 有三种模式,各自引起的读写行为也不同,容後再述:
     0 is Export mode
     1 is Import mode
     2 is Linked mode (full update capabilities)
    

      这里特别要说明的就是 IMEX 参数了,因为不同的模式代表著不同的读写行为:

      当 IMEX=0 时为“汇出模式”,这个模式开启的 Excel 档案只能用来做“写入”用途。

      当 IMEX=1 时为“汇入模式”,这个模式开启的 Excel 档案只能用来做“读取”用途。

      当 IMEX=2 时为“连結模式”,这个模式开启的 Excel 档案可同时支援“读取”与“写入”用途。


        //导入excel     
        private void toolStripButton1_Click(object sender, EventArgs e)
        {         
            try
            {                
                DataSet ds = xsldata();
                if (ds == null)    //如果录入dataset的数据为空(没有点击导入或者直接退出),则{}不执行
                { }
                else
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        dataGridView1.Rows.Add((i + 1).ToString(),
                            ds.Tables[0].Rows[i][0].ToString(),
                            ds.Tables[0].Rows[i][1].ToString(),
                            ds.Tables[0].Rows[i][2].ToString(),
                            ds.Tables[0].Rows[i][3].ToString(),
                            ds.Tables[0].Rows[i][4].ToString(),
                            ds.Tables[0].Rows[i][5].ToString(),
                            ds.Tables[0].Rows[i][6].ToString(),
                            ds.Tables[0].Rows[i][7].ToString(),
                            ds.Tables[0].Rows[i][8].ToString(),
                            ds.Tables[0].Rows[i][9].ToString(),
                            ds.Tables[0].Rows[i][10].ToString()
                           );
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("" + ex.ToString() + "导入文件时出错,文件可能正被打开", "提示");
                return;
            }
 
导入CSV 文件 绑定:
 
方式一:

 string mystring = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Directory.GetParent(filePath) + ";Extended Properties='Text;FMT=Delimited;HDR=Yes;IMEX=1;'";          

   //string fUname = fUExcel.FileName;            

string fUname = filePath.Substring(filePath.LastIndexOf("\\") + 1);            

string query = "SELECT * FROM [" + fUname + "]";

            OleDbConnection cnnxls = new OleDbConnection();       

      cnnxls.ConnectionString = mystring;            

cnnxls.Open();//打开连接            

OleDbDataAdapter oleAdapter = new OleDbDataAdapter(query, cnnxls);       

      DataSet ds = new DataSet();           

  oleAdapter.Fill(ds);         

    dtResult = dtReaderEbay(ds);           /读取对象

   dgbom.DataSource = dtResult;            

dgbom.DataBind();            

ds.Dispose();           

  cnnxls.Close(); 

方式二:

 using (StreamReader sr = new StreamReader(filePath, System.Text.Encoding.GetEncoding("GB2312")))
            {
                string strLine = string.Empty;
                string [] temp;               
                while ((strLine = sr.ReadLine()) != null) {
                    temp=strLine.Split(','); //将行内容分割到temp数组
                    dtebay.Rows.Add(Sys_User.UserAccount.ToString().Trim(), temp[2], temp[3], temp[4], temp[5],
                                    temp[6], temp[7], temp[8], temp[9], temp[10],
                                    temp[11], temp[12], temp[31], this.DropShippingMethod.SelectedValue.ToString().Trim());
                }
                //dvTable = dtReaderEbay(db);
                dtebay.Rows.RemoveAt(0);
                dgbom.DataSource = dtebay;
                dgbom.DataBind();
            }   

/// <summary>
    /// 文件上传
    /// </summary>
    /// <returns></returns>
    private string UploadFile()
    {
        #region 上传文件
        HttpPostedFile p = fUExcel.PostedFile;
        string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetFileName(p.FileName);
        if (!Directory.Exists(Server.MapPath(@"~/upload" + "//")))
        {
            Directory.CreateDirectory(Server.MapPath(@"~/upload" + "//"));
        }
        string filePath = Server.MapPath(@"~/upload" + "//" + filename);
        fUExcel.SaveAs(filePath);
        return filePath;
        #endregion
    }

前台:

<asp:FileUpload ID="fUExcel" runat="server" />

 
 
原文地址:https://www.cnblogs.com/quanxie/p/2995658.html