C#访问Excel工作表

时间:2009-09-23 19:19:48

标签: c# excel ms-office connection-string

这是访问MS Office Excel 2007文件的正确方法吗?

        String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + 
    "Data Source=" + file_path + ";Extended Properties=Excel 8.0;";

如果是这样,我如何访问某个工作表并插入行?也欢迎链接。

3 个答案:

答案 0 :(得分:1)

有一篇关于codeproject的文章 - http://www.codeproject.com/KB/office/excel_using_oledb.aspx - 应该让你开始

答案 1 :(得分:1)

连接字符串

  connectionString = @"provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + @";Extended Properties=""Excel 12.0;HDR=YES;IMEX=1""";

阅读数据

 excelConnection = new System.Data.OleDb.OleDbConnection(connectionString);
        excelConnection.Open();
        dbSchema = excelConnection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
        firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();
        strSQL = "SELECT * FROM [" + firstSheetName + "]";
        da = new OleDbDataAdapter(strSQL, excelConnection);
        da.Fill(dt);

编写数据,请参阅Excel Generation,但这会使用自动化。这可能有所帮助。

答案 2 :(得分:1)

您可以使用Excel Interop(Microsoft.Office.Interop.Excel):

以下是一些代码片段:

object missing = (object) Type.Missing;

Application app = new Application();

Workbooks books = app.Workbooks;

Workbook book = books.Open("somefile.xls", missing, missing, missing, missing, missing, missing,
            missing, missing, missing, missing, missing, missing, missing, missing);

Worksheet sheet = (Worksheet)book.Worksheets[1];

它有一些奇怪的东西(比如那些“缺失”的参数),但它的工作非常顺利。如果采用这种方法,请注意EXCEL.exe进程不会孤立。