.net 中访问 excel文件的两种方式

本文介绍了一种使用OleDB连接Excel文件并从中读取数据的方法,并提供了完整的C#代码示例。此外,还介绍了如何利用Microsoft.Office.Core.Excel库进行更高级的操作。
 1, OleDB, look in to the code sample following:
public static String ReadIn ( string sheetName )
{
    StringBuilder output 
= new StringBuilder( 5124096 );
    StringWriter writer 
= new StringWriter( output );

    OpenFileDialog dialog 
= new OpenFileDialog( );
    dialog.Filter 
= @"Excel Files (*.xls)|*.xls|All Files (*.*)|*.*";
    
if ( ( dialog.ShowDialog( ) == DialogResult.OK ) )
    
{
        
string filename = dialog.FileName;
        
string connectionString;
        
string Query;
        MessageBox.Show( filename );
        connectionString 
= ( "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
                    
+ ( filename + ( ";Extended Properties=" + ( '"' + ( "Excel 8.0;HDR=Yes;IMEX=1" + ( '"' + ";" ) ) ) ) ) );
        Query 
= ( "SELECT * FROM " + sheetName );
        Query 
= String.Format( "SELECT * FROM [{0}$]", sheetName );
        
try
        
{
            OleDbConnection connection 
= new OleDbConnection( connectionString );
            OleDbCommand command 
= new OleDbCommand( Query, connection );
            OleDbDataReader reader;
            connection.Open( );
            reader 
= command.ExecuteReader( );
            
while ( reader.Read() )
            
{
                writer.Write( reader.GetValue( 
0 ).ToString( ) + " " );
                writer.Write( reader.GetValue( 
1 ).ToString( ) + " " );
                writer.Write( reader.GetValue( 
2 ).ToString( ) + " " );
                writer.Write( reader.GetValue( 
3 ).ToString( ) + " " );
                writer.WriteLine( );
            }

            reader.Close( );
            connection.Close( );
        }

        
catch ( Exception ex )
        
{
            writer.WriteLine( ex.Message );
        }

        
return output.ToString( );
    }

    
return @"";
}


2, Using Microsoft.Office.Core.Excel.dll:
  1. Add Microsoft.Office.Core.Excel.dll as a reference to your porject.

  2. Start using the Excel functionality using the Microsoft.Office.Core.Excel namespace.

  3. You can use the Workbook class to open the xls file and then find your WorkSheet and go to the different cells using Rows, Columns or Cells.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值