Excel与DataGridView

转自http://blog.csdn.net/lpy1016lc/article/details/13275415

 

- C# winform Excel 数据导入

class ExcelCtrl
    {
        #region 将DataGridView控件中数据导出到Excel

        /// <summary>
        /// 将DataGridView控件中数据导出到Excel
        /// </summary>
        /// <param name="gridView">DataGridView对象</param>
        /// <param name="isShowExcle">是否显示Excel界面</param>
        /// <returns></returns>
        public bool ExportDataGridview(DataGridView gridView, bool isShowExcle,string path)
        {
            if (gridView.Rows.Count == 0)
                return false;
            //建立Excel对象
            Excel.Application excel = new Excel.Application();
            Excel.Workbook myWorkBook=excel.Application.Workbooks.Add(true);
            excel.Visible = isShowExcle;

            //生成字段名称
            for (int i = 0; i < gridView.ColumnCount; i++)
            {
                excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText;
            }
            //填充数据
            for (int i = 0; i < gridView.Rows.Count - 1; i++)
            {
                for (int j = 0; j < gridView.Columns.Count; j++)
                {
                    if (gridView[j, i].ValueType == typeof(string))
                    {
                        excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString();
                    }
                    else
                    {
                        excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString();
                    }
                }
            }
            object missing = System.Reflection.Missing.Value;
            excel.ActiveWorkbook.Saved = true;
            excel.ActiveWorkbook.SaveAs(path,
                Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel9795,
                missing, missing, false,
                false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
                missing, missing, missing, missing, missing);
            myWorkBook.Close(missing, missing, missing);
            myWorkBook = null;
            excel.Quit();

            return true;
        }

        #endregion

 

 

     

   #region 将DataGridView控件中数据导出到Excel,excel格式本身就可以充当数据库,所以我以这种方式进行查询读取

 

        public DataTable ImportExcel(string path)
        {
            string Connecstr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path
                + ";Extended Properties='Excel 8.0;HDR=YES; IMEX=1'";
            OleDbConnection Con = new OleDbConnection(Connecstr);
            Con.Open();
            string strCommand = "SELECT   *   FROM   [Sheet1$]";
            OleDbDataAdapter adapter = new OleDbDataAdapter(strCommand, Con);
            DataSet DS = new DataSet();
            adapter.Fill(DS, "[Sheet1$]");
            DataTable dt=DS.Tables[0];
            Con.Close();
            return dt;
        }

        #endregion
    }

 

 

 

- ASP.NET Excel数据导入功能

 

protected void btnImport_Click(object sender, EventArgs e)

    {
         if  (FileUpload1.HasFile  ==   false ) // HasFile用来检查FileUpload是否有指定文件 
        {
            Response.Write( " <script>alert('请您选择Excel文件')</script>  " );
             return ; // 当无文件时,返回 
        }
         string  IsXls  = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower(); //System.IO.Path.GetExtension获得文件的扩展名 
         if  (IsXls  !=   " .xls " )
        {
            Response.Write( " <script>alert('只可以选择Excel文件')</script> " );
             return ; // 当选择的不是Excel文件时,返回 
        }
         string  filename  =  FileUpload1.FileName;               // 获取Execle文件名  DateTime日期函数 
         string  savePath  =  Server.MapPath(( " upfiles\\ " )  +  filename); //Server.MapPath 获得虚拟服务器相对路径 
        FileUpload1.SaveAs(savePath);                         // SaveAs 将上传的文件内容保存在服务器上 
        DataSet ds  =  ExcelSqlConnection(savePath, filename);            // 调用自定义方法 
        DataRow[] dr  =  ds.Tables[ 0 ].Select();             // 定义一个DataRow数组 
         int  rowsnum  =  ds.Tables[ 0 ].Rows.Count;
         if  (rowsnum  ==   0 )
        {
            Response.Write( " <script>alert('Excel表为空表,无数据!')</script> " );    // 当Excel表为空时,对用户进行提示 
        }
         else 
         {
             for  ( int  i  =   0 ; i  <  dr.Length; i ++ )
            {
                 // 前面除了你需要在建立一个“upfiles”的文件夹外,其他的都不用管了,你只需要通过下面的方式获取Excel的值,然后再将这些值用你的方式去插入到数据库里面 
                 string  title  =  dr[i][ " 标题 " ].ToString();
                 string  linkurl  =  dr[i][ " 链接地址 " ].ToString();
                 string  categoryname  =  dr[i][ " 分类 " ].ToString();
                 string  customername  =  dr[i][ " 内容商 " ].ToString();
                
                 // Response.Write("<script>alert('导入内容:" + ex.Message + "')</script>"); 
            }
            Response.Write( " <script>alert('Excle表导入成功!');</script> " );
        }

    }

 


     

#region  连接Excel  读取Excel数据   并返回DataSet数据集合 
      ///   <summary> 
      ///  连接Excel  读取Excel数据   并返回DataSet数据集合
     ///   </summary> 
      ///   <param name="filepath"> Excel服务器路径 </param> 
      ///   <param name="tableName"> Excel表名称 </param> 
      ///   <returns></returns> 
     public   static  System.Data.DataSet ExcelSqlConnection( string  filepath,  string tableName)
    {
         string  strCon  =   " Provider=Microsoft.Jet.OLEDB.4.0;Data Source= "   +  filepath  +  " ;Extended Properties='Excel 8.0;HDR=YES;IMEX=1' " ;
        OleDbConnection ExcelConn  =   new  OleDbConnection(strCon);
         try 
         {
             string  strCom  =   string .Format( " SELECT * FROM [Sheet1$] " );
            ExcelConn.Open();
            OleDbDataAdapter myCommand  =   new  OleDbDataAdapter(strCom, ExcelConn);
            DataSet ds  =   new  DataSet();
            myCommand.Fill(ds,  " [ "   +  tableName  +   " $] " );
            ExcelConn.Close();
             return  ds;
        }
         catch 
         {
            ExcelConn.Close();
             return   null ;
        }
    }

    #endregion

 

 

 

 

 

 

1.方法一:采用OleDB读取EXCEL文件:
  

///把EXCEL文件当做一个数据源来进行数据的读取操作,实例如下:
public DataSet ExcelToDS(string Path) 
{ 
 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;"; 
 OleDbConnection conn = new OleDbConnection(strConn); 
 conn.Open();   
 string strExcel = "";    
 OleDbDataAdapter myCommand = null; 
 DataSet ds = null; 
 strExcel="select * from [sheet1$]"; 
 myCommand = new OleDbDataAdapter(strExcel, strConn); 
 ds = new DataSet(); 
 myCommand.Fill(ds,"table1");    
 return ds; 
} 
///对于EXCEL中的表即sheet([sheet1$])如果不是固定的可以使用下面的方法得到 
 string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;"; 
 OleDbConnection conn = new OleDbConnection(strConn); 
 DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,null);
 string tableName=schemaTable.Rows[0][2].ToString().Trim();  

///另外:也可进行写入EXCEL文件,实例如下:
public void DSToExcel(string Path,DataSet oldds) 
{ 
 //先得到汇总EXCEL的DataSet 主要目的是获得EXCEL在DataSet中的结构 
 string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source ="+path1+";Extended Properties=Excel 8.0" ; 
 OleDbConnection myConn = new OleDbConnection(strCon) ; 
 string strCom="select * from [Sheet1$]"; 
 myConn.Open ( ) ; 
 OleDbDataAdapter myCommand = new OleDbDataAdapter ( strCom, myConn ) ; 
 ystem.Data.OleDb.OleDbCommandBuilder builder=new OleDbCommandBuilder(myCommand); 
 //QuotePrefix和QuoteSuffix主要是对builder生成InsertComment命令时使用。 
 builder.QuotePrefix="[";     //获取insert语句中保留字符(起始位置) 
 builder.QuoteSuffix="]"; //获取insert语句中保留字符(结束位置) 
 DataSet newds=new DataSet(); 
 myCommand.Fill(newds ,"Table1") ; 
 for(int i=0;i<oldds.Tables[0].Rows.Count;i++) 
 { 
  //在这里不能使用ImportRow方法将一行导入到news中,因为ImportRow将保留原来DataRow的所有设置(DataRowState状态不变)。
  /// 在使用ImportRow后newds内有值,但不能更新到Excel中因为所有导入行的DataRowState!=Added 
  DataRow nrow=aDataSet.Tables["Table1"].NewRow(); 
  for(int j=0;j<newds.Tables[0].Columns.Count;j++) 
  { 
   nrow[j]=oldds.Tables[0].Rows[i][j]; 
  } 
  newds.Tables["Table1"].Rows.Add(nrow); 
 } 
 myCommand.Update(newds,"Table1"); 
 myConn.Close(); 
}

 


2.方法二:引用的com组件:Microsoft.Office.Interop.Excel.dll   读取EXCEL文件

  ///首先是Excel.dll的获取,将Office安装目录下的Excel.exe文件Copy到DotNet的bin目录下,cmd到该目录下,运行 TlbImp EXCEL.EXE Excel.dll 得到Dll文件。 点击此处下载此文      件:/Files/songliang/DLL文件.rar
   ///再在项目中添加引用该dll文件.

    //读取EXCEL的方法   (用范围区域读取数据)
    private void OpenExcel(string strFileName)
    {
        object missing = System.Reflection.Missing.Value;
        Application excel = new Application();//lauch excel application
        if (excel == null)
        {
            Response.Write("<script>alert('Can't access excel')</script>");
        }
        else
        {
            excel.Visible = false;  excel.UserControl = true;
            // 以只读的形式打开EXCEL文件
            Workbook wb = excel.Application.Workbooks.Open(strFileName, missing, true, missing, missing, missing,
             missing, missing, missing, true, missing, missing, missing, missing, missing);
            //取得第一个工作薄
            Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1);

            //取得总记录行数   (包括标题列)
            int rowsint = ws.UsedRange.Cells.Rows.Count; //得到行数
            //int columnsint = mySheet.UsedRange.Cells.Columns.Count;//得到列数

            //取得数据范围区域  (不包括标题列)  
            Range rng1 = ws.Cells.get_Range("B2", "B" + rowsint);   //item

            Range rng2 = ws.Cells.get_Range("K2", "K" + rowsint);  //Customer
            object[,] arryItem= (object[,])rng1.Value2;   //get range's value
            object[,] arryCus = (object[,])rng2.Value2;   
            //将新值赋给一个数组
            string[,] arry = new string[rowsint-1, 2];
            for (int i = 1; i <= rowsint-1; i++)
            {
                //Item_Code列
                arry[i - 1, 0] =arryItem[i, 1].ToString();
                //Customer_Name列
                arry[i - 1, 1] = arryCus[i, 1].ToString();
            }
            Response.Write(arry[0, 0] + "  /  " + arry[0, 1] + "#" + arry[rowsint - 2, 0] + "  /  " + arry[rowsint - 2, 1]);
        }
         excel.Quit();  excel = null;
        Process[] procs = Process.GetProcessesByName("excel");

        foreach (Process pro in procs)
        {
            pro.Kill();//没有更好的方法,只有杀掉进程
        }
        GC.Collect();
    }

 

3.方法三:将EXCEL文件转化成CSV(逗号分隔)的文件,用文件流读取(等价就是读取一个txt文本文件)。
          

 ///先引用命名空间:using System.Text;和using System.IO;
           FileStream fs = new FileStream("d:\\Customer.csv", FileMode.Open, FileAccess.Read, FileShare.None);
           StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding(936));

           string str = "";
           string s = Console.ReadLine();
           while (str != null)
           {    str = sr.ReadLine();
                string[] xu = new String[2];
                xu = str.Split(',');
                string ser = xu[0]; 
                string dse = xu[1];                if (ser == s)
                {  Console.WriteLine(dse);break;
                }
           }   sr.Close();
  
          ///另外也可以将数据库数据导入到一个txt文件,实例如下:
    
        //txt文件名
        string fn = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + "PO014" + ".txt";

        OleDbConnection con = new OleDbConnection(conStr); 
        con.Open();
        string sql = "select  ITEM,REQD_DATE,QTY,PUR_FLG,PO_NUM from TSD_PO014";        
       //OleDbCommand mycom = new OleDbCommand("select * from TSD_PO014", mycon);
        //OleDbDataReader myreader = mycom.ExecuteReader();  //也可以用Reader读取数据
        DataSet ds = new DataSet();
        OleDbDataAdapter oda = new OleDbDataAdapter(sql, con);
        oda.Fill(ds, "PO014");
        DataTable dt = ds.Tables[0];

        FileStream fs = new FileStream(Server.MapPath("download/" + fn), FileMode.Create, FileAccess.ReadWrite);
        StreamWriter strmWriter = new StreamWriter(fs);    //存入到文本文件中 
 
        //把标题写入.txt文件中 
        //for (int i = 0; i <dt.Columns.Count;i++)
        //{
        //    strmWriter.Write(dt.Columns[i].ColumnName + "  ");
        //}
        
        foreach (DataRow dr in dt.Rows)
        {
            string str0, str1, str2, str3;
            string str = "|";  //数据用"|"分隔开
            str0 = dr[0].ToString();
            str1 = dr[1].ToString();
            str2 = dr[2].ToString();
            str3 = dr[3].ToString();
            str4 = dr[4].ToString().Trim();
            strmWriter.Write(str0);
            strmWriter.Write(str);
            strmWriter.Write(str1);
            strmWriter.Write(str);
            strmWriter.Write(str2);
            strmWriter.Write(str);
            strmWriter.Write(str3);
            strmWriter.WriteLine();  //换行
        }
        strmWriter.Flush();
        strmWriter.Close();
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }

 

posted @ 2017-06-02 16:38  是什么让人懒惰  阅读(1421)  评论(0编辑  收藏  举报