Excel的相关操作

有关Excel的操作
 
在执行Excel的操作时,首先加入引用:microsoft.office.iterop.Excel.要引用数据库连接时加引用:System.date.sqlClient
从Excel中读出数据到DatagridView中:
public   void   Reader(DataGridView dgv)
        {
            
try
            {
                
string  strConn  =   " Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\di\\桌面\\SMAPLE_GD2_master_data.xls;Extended Properties=Excel 8.0 " ;
                OleDbConnection OleDB 
=   new  OleDbConnection(strConn);
                OleDbDataAdapter OleDat 
=   new  OleDbDataAdapter( " select * from [ConfigSheetLabel$] " , OleDB);
                DataTable dt 
=   new  DataTable();
                OleDat.Fill(dt);
               dgv.DataSource
=  dt.DefaultView;
            }
            
catch  (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }      
        }
 
将DataGridView中的数据写入到Excel中:
public   bool  Writer(DataGridView dgv,  bool  isShowExcel)
        {
            
if  (dgv.Rows.Count  <   1 )
            {
                
return   false ;
            }
            Excel.Application excel 
=   new  Microsoft.Office.Interop.Excel.Application();
            excel.Application.Workbooks.Add(
true );
            excel.Visible 
=  isShowExcel;
            
for  ( int  i  =   0 ; i  <  dgv.ColumnCount; i ++ )
            {
                excel.Cells[
1 , i  +   1 =  dgv.Columns[i].HeaderText;
            }
            
for  ( int  i  =   0 ; i  <  dgv.Rows.Count  -   1 ; i ++ )
            {
                
for  ( int  j  =   0 ; j  <  dgv.ColumnCount; j ++ )
                {
                    
if  (dgv[j, i].ValueType  ==   typeof ( string ))
                    {
                        excel.Cells[i 
+   2 , j  +   1 =   ""   +  dgv[j, i].Value.ToString();
                    }
                    
else
                    {
                        excel.Cells[i 
+   2 , j  +   1 =  dgv[j, i].Value.ToString();
                    }
                }
            }
            
return   true ;
        }
 

你可能感兴趣的:(Excel)