Excel to DataGridView  using excel 2007 不指定

Else , 2008/06/20 17:14 , 代码片段,演示也有 , Comments(0) , Reads(2286) , Via Original
[codes=C#]private void Form4_Load(object sender, EventArgs e)

        {

            object oMissing = Missing.Value;

            Microsoft.Office.Interop.Excel.Application ExcelObj =
                new Microsoft.Office.Interop.Excel.Application();

            Microsoft.Office.Interop.Excel.Workbook WBook;

            Microsoft.Office.Interop.Excel.Worksheet WSheet;

            Microsoft.Office.Interop.Excel.Range Selection;

            WBook = ExcelObj.Workbooks.Open(@"c:\test\1.xlsx",

                oMissing, oMissing, oMissing, oMissing, oMissing,

                oMissing, oMissing, oMissing, oMissing, oMissing,

                oMissing, oMissing, oMissing, oMissing);



            WSheet = (Microsoft.Office.Interop.Excel.Worksheet)WBook.Sheets.get_Item(1);

            // Conversion

            Selection = WSheet.Cells;

            Selection.Select();

            Selection.NumberFormat = "@";

            WBook.Save();



            string ConnectionString =

                "Provider=Microsoft.ACE.OLEDB.12.0;" +

                "Data Source=" + @"c:\test\1.xlsx;" +

                "Excel 12.0;HDR=YES;";



            OleDbConnection ExcelConnection = new OleDbConnection(ConnectionString);

            OleDbDataAdapter ad = new OleDbDataAdapter();



            ad.SelectCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", ExcelConnection);

            DataTable dt = new DataTable();

            ad.Fill(dt);



            this.dataGridView1.DataSource = dt;

        }

[/codes]
Tags: , ,
Add a comment

Nickname

Site URI

Email

Enable HTML Enable UBB Enable Emots Hidden Remember [Login] [Register]