是否有免费或开源库直接从C#程序读取Excel文件(.xls)?
它不需要太花哨,只需选择一个工作表并将数据作为字符串读取.到目前为止,我一直在使用Excel的Export to Unicode文本功能,并解析生成的(制表符分隔的)文件,但我想消除手动步骤.
var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory()); var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName); var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString); var ds = new DataSet(); adapter.Fill(ds, "anyNameHere"); DataTable data = ds.Tables["anyNameHere"];
这就是我经常使用的.它有点不同,因为我通常在表的编辑中粘贴AsEnumerable():
var data = ds.Tables["anyNameHere"].AsEnumerable();
因为这允许我使用LINQ从字段中搜索和构建结构.
var query = data.Where(x => x.Field("phoneNumber") != string.Empty).Select(x => new MyContact { firstName= x.Field ("First Name"), lastName = x.Field ("Last Name"), phoneNumber =x.Field ("Phone Number"), });
如果只是Excel文件中包含的简单数据,您可以通过ADO.NET读取数据.请参阅此处列出的连接字符串:
http://www.connectionstrings.com/?carrier=excel2007 或 http://www.connectionstrings.com/?carrier=excel
-Ryan
更新:然后您可以通过类似的方式阅读工作表 select * from [Sheet1$]
ADO.NET方法快速而简单,但它有一些你应该注意的怪癖,特别是关于DataTypes的处理方式.
这篇优秀的文章将帮助您避免一些常见的陷阱:http: //blog.lab49.com/archives/196
这是我用于Excel 2003的内容:
Dictionaryprops = new Dictionary (); props["Provider"] = "Microsoft.Jet.OLEDB.4.0"; props["Data Source"] = repFile; props["Extended Properties"] = "Excel 8.0"; StringBuilder sb = new StringBuilder(); foreach (KeyValuePair prop in props) { sb.Append(prop.Key); sb.Append('='); sb.Append(prop.Value); sb.Append(';'); } string properties = sb.ToString(); using (OleDbConnection conn = new OleDbConnection(properties)) { conn.Open(); DataSet ds = new DataSet(); string columns = String.Join(",", columnNames.ToArray()); using (OleDbDataAdapter da = new OleDbDataAdapter( "SELECT " + columns + " FROM [" + worksheet + "$]", conn)) { DataTable dt = new DataTable(tableName); da.Fill(dt); ds.Tables.Add(dt); } }
Excel Data Reader怎么样?
http://exceldatareader.codeplex.com/
我在生产环境中使用它来将大量数据从各种Excel文件中提取到SQL Server Compact中.它运作良好,而且非常强大.
这是我几年前使用.NET 1.1在C#中编写的一些代码.不确定这是否正是你所需要的(可能不是我最好的代码:)).
using System; using System.Data; using System.Data.OleDb; namespace ExportExcelToAccess { ////// Summary description for ExcelHelper. /// public sealed class ExcelHelper { private const string CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=;Extended Properties=\"Excel 8.0;HDR=Yes;\";"; public static DataTable GetDataTableFromExcelFile(string fullFileName, ref string sheetName) { OleDbConnection objConnection = new OleDbConnection(); objConnection = new OleDbConnection(CONNECTION_STRING.Replace(" ", fullFileName)); DataSet dsImport = new DataSet(); try { objConnection.Open(); DataTable dtSchema = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); if( (null == dtSchema) || ( dtSchema.Rows.Count <= 0 ) ) { //raise exception if needed } if( (null != sheetName) && (0 != sheetName.Length)) { if( !CheckIfSheetNameExists(sheetName, dtSchema) ) { //raise exception if needed } } else { //Reading the first sheet name from the Excel file. sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString(); } new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", objConnection ).Fill(dsImport); } catch (Exception) { //raise exception if needed } finally { // Clean up. if(objConnection != null) { objConnection.Close(); objConnection.Dispose(); } } return dsImport.Tables[0]; #region Commented code for importing data from CSV file. // string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=" + System.IO.Path.GetDirectoryName(fullFileName) +";" +"Extended Properties=\"Text;HDR=YES;FMT=Delimited\""; // // System.Data.OleDb.OleDbConnection conText = new System.Data.OleDb.OleDbConnection(strConnectionString); // new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(fullFileName).Replace(".", "#"), conText).Fill(dsImport); // return dsImport.Tables[0]; #endregion } /// /// This method checks if the user entered sheetName exists in the Schema Table /// /// Sheet name to be verified /// schema table private static bool CheckIfSheetNameExists(string sheetName, DataTable dtSchema) { foreach(DataRow dataRow in dtSchema.Rows) { if( sheetName == dataRow["TABLE_NAME"].ToString() ) { return true; } } return false; } } }
Koogra是一个用C#编写的开源组件,用于读写Excel文件.
虽然你特意要求.xls,暗示较旧的文件格式,对于OpenXML格式(例如xlsx),我强烈推荐OpenXML SDK(http://msdn.microsoft.com/en-us/library/bb448854.aspx)
我在C#中做了大量的Excel文件阅读,我们使用了两种方法:
COM API,您可以直接访问Excel的对象并通过方法和属性对其进行操作
允许像数据库一样使用Excel的ODBC驱动程序.
后一种方法要快得多:读取20列和200行的大表通过COM需要30秒,通过ODBC需要半秒.所以如果您需要的只是数据,我会推荐数据库方法.
干杯,
卡尔
ExcelMapper是一个开源工具(http://code.google.com/p/excelmapper/),可用于将Excel工作表读取为强类型对象.它支持xls和xlsx格式.
我想展示一个用.NET读取xls/xlsx文件的简单方法.我希望以下内容对您有所帮助.
private DataTable ReadExcelToTable(string path) { //Connection String string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; //the same name //string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + //";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; using(OleDbConnection conn = new OleDbConnection(connstring)) { conn.Open(); //Get All Sheets Name DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,"Table"}); //Get the First Sheet Name string firstSheetName = sheetsName.Rows[0][2].ToString(); //Query String string sql = string.Format("SELECT * FROM [{0}]",firstSheetName); OleDbDataAdapter ada =new OleDbDataAdapter(sql,connstring); DataSet set = new DataSet(); ada.Fill(set); return set.Tables[0]; } }
代码来自文章:http://www.c-sharpcorner.com/uploadfile/d2dcfc/read-excel-file-with-net/.您可以从中获取更多详细信息.