如何在C#中的Excel上运行单元格?
我可以如何运行Excel中的单元格(而不是.csv)并读取单元格值? 我需要运行所有的单元格。 提前致谢。
这是一个示例 :
Excel.Application oXL; Excel._Workbook oWB; Excel._Worksheet oSheet; Excel.Range oRng; //Start Excel and get Application object. oXL = new Excel.Application(); oXL.Visible = true; //Get a new workbook. oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value )); oSheet = (Excel._Worksheet)oWB.ActiveSheet; //Add table headers going cell by cell. oSheet.Cells[1, 1] = "First Name";
这里有一个使用ADO.NET的方法:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\myfile.xls;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";"; string provider = "System.Data.OleDb"; DbProviderFactory factory = DbProviderFactories.GetFactory(provider); DbConnection connection = factory.CreateConnection(); connection.ConnectionString = connectionString; connection.Open(); DbCommand command = connection.CreateCommand(); command.CommandText = "SELECT * FROM [Sheet1$]" DbDataReader reader = command.ExecuteReader(); while(reader.read()) { // process row }
查看ConnectionString.com获取有关连接string设置的详细信息(例如,Excel 2007 略有不同 )。 在command
设置commandText
属性时,您可以设置更复杂的查询( SELECT * from [Sheet1$] where someColumn <> someValue and someOtherColumn > someOtherValue
)。
这种方法有一个很好的优点,如果你已经熟悉ADO.NET,你可以使用你在那里获得的知识。 而且,Excel不需要安装在机器上。
我认为最好的办法是把excel当成ADO.NET数据源。 这里是一个例子: http : //www.knowdotnet.com/articles/exceldatasource.html 。
这种方法让您轻松查询Excel表格中的数据,甚至不需要安装Microsoft Excel。
- Excel Interop COMException HRESULT:0x800A03EC访问隐藏的单元格时
- .NET中的XLSX生成 – Microsoft Excel对象库免费替代
- 使用VBA Excel进行比较,复制和粘贴
- 如何使用SpreadsheetLight正确分组Excel中的行?
- 可以使用例如Microsoft.Office.Interop.Excel构build的VSTO项目在未安装Office的计算机上运行吗?
- 安装/删除2013testing版后,断开了Excel Interop COM程序集
- 如何处理C#中excel工作表的另存为对话框
- Excel:在Excel中获取周围的命名区域
- 我如何从Excel工作簿中去除macros?