C#访问Excel工作表
这是访问MS Office Excel 2007文件的正确方法吗?
String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + file_path + ";Extended Properties=Excel 8.0;";
如果是这样,我如何访问某个工作表并插入行? 链接也欢迎。
有一篇关于codeproject的文章 – http://www.codeproject.com/KB/office/excel_using_oledb.aspx – 应该让你开始
您可以使用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进程不会孤立。
连接string
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生成这个虽然使用自动化。 这可能有帮助。