Rob*_*son 153
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"];
Run Code Online (Sandbox Code Playgroud)
这就是我经常使用的.它有点不同,因为我通常在表的编辑中粘贴AsEnumerable():
var data = ds.Tables["anyNameHere"].AsEnumerable();
Run Code Online (Sandbox Code Playgroud)
因为这允许我使用LINQ从字段中搜索和构建结构.
var query = data.Where(x => x.Field<string>("phoneNumber") != string.Empty).Select(x =>
new MyContact
{
firstName= x.Field<string>("First Name"),
lastName = x.Field<string>("Last Name"),
phoneNumber =x.Field<string>("Phone Number"),
});
Run Code Online (Sandbox Code Playgroud)
Rya*_*ley 83
如果只是Excel文件中包含的简单数据,您可以通过ADO.NET读取数据.请参阅此处列出的连接字符串:
http://www.connectionstrings.com/?carrier=excel2007 或 http://www.connectionstrings.com/?carrier=excel
-Ryan
更新:然后您可以通过类似的方式阅读工作表 select * from [Sheet1$]
Ian*_*son 27
ADO.NET方法快速而简单,但它有一些你应该注意的怪癖,特别是关于DataTypes的处理方式.
这篇优秀的文章将帮助您避免一些常见的陷阱:http: //blog.lab49.com/archives/196
Dmi*_*man 22
这是我用于Excel 2003的内容:
Dictionary<string, string> props = new Dictionary<string, string>();
props["Provider"] = "Microsoft.Jet.OLEDB.4.0";
props["Data Source"] = repFile;
props["Extended Properties"] = "Excel 8.0";
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> 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);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 21
Excel Data Reader怎么样?
http://exceldatareader.codeplex.com/
我在生产环境中使用它来将大量数据从各种Excel文件中提取到SQL Server Compact中.它运作良好,而且非常强大.
hit*_*tec 16
这是我几年前使用.NET 1.1在C#中编写的一些代码.不确定这是否正是你所需要的(可能不是我最好的代码:)).
using System;
using System.Data;
using System.Data.OleDb;
namespace ExportExcelToAccess
{
/// <summary>
/// Summary description for ExcelHelper.
/// </summary>
public sealed class ExcelHelper
{
private const string CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FILENAME>;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("<FILENAME>", 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
}
/// <summary>
/// This method checks if the user entered sheetName exists in the Schema Table
/// </summary>
/// <param name="sheetName">Sheet name to be verified</param>
/// <param name="dtSchema">schema table </param>
private static bool CheckIfSheetNameExists(string sheetName, DataTable dtSchema)
{
foreach(DataRow dataRow in dtSchema.Rows)
{
if( sheetName == dataRow["TABLE_NAME"].ToString() )
{
return true;
}
}
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Haf*_*hor 12
虽然你特意要求.xls,暗示较旧的文件格式,对于OpenXML格式(例如xlsx),我强烈推荐OpenXML SDK(http://msdn.microsoft.com/en-us/library/bb448854.aspx)
我在C#中做了大量的Excel文件阅读,我们使用了两种方法:
后一种方法要快得多:读取20列和200行的大表通过COM需要30秒,通过ODBC需要半秒.所以如果您需要的只是数据,我会推荐数据库方法.
干杯,
卡尔
小智 6
我想展示一个用.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/.您可以从中获取更多详细信息.
归档时间: |
|
查看次数: |
459772 次 |
最近记录: |