using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Data; using System.Data.OleDb; namespace ExcelReader { public class ExcelHelper { private OleDbConnection conn = new OleDbConnection(); public ExcelHelper(string excelPath) { string connectionStr = string.Format(ConfigurationManager.AppSettings["ConnectionString"], excelPath); conn.ConnectionString = connectionStr; } public DataTable GetExcelTable() { OleDbCommand cmd = conn.CreateCommand(); cmd.CommandText = "select * from [Sheet1$]"; DataTable table = new DataTable(); OleDbDataAdapter oda = new OleDbDataAdapter(cmd); oda.Fill(table); foreach (DataRow row in table.Rows) { if (!(row[0].ToString()).Equals("交易日期")) { row.Delete(); } else { break; } } for (int i = 0; i < table.Columns.Count; i++) { table.Columns[i].ColumnName = table.Rows[0][i].ToString(); } table.Rows[0].Delete(); table = table.GetChanges(DataRowState.Unchanged); return table; } } }
经过实验,可以获取数据表~
下面是连接字符串:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="ConnectionString" value="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=NO;IMEX=1'"/> </appSettings> </configuration>
赞~ 最喜欢看代码了,一目了然,比理论知识形象多了。
@小刺猬001: 哈哈,多谢支持
@龙葛格: 谢谢啊 我来试试
string StrConExcel2007 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=YES\"" HDR=YES的时候,第一行会被读成列头 如果你第一行就是数据的话,请设置HDR=NO
@斯拉克: 。。你看、我都给你说了
读取出来的时候循环表可以控制从哪一行开始去读 控制到这一行就去读然后取列头就可以了
判断条件,第五行,第一列,值等于“交易”日期的时候,才开始读取。
从第五行开始循环就ok了
用NPOI来读吧
http://npoi.codeplex.com/
指定行索引读取
http://git.oschina.net/lishilei0523/SD.Toolkits
public static DataTable ImportCompareMeanExcel(string strFilePath)
{
Workbook workbook = new Workbook();
DataTable dtExcel = null;
try
{
workbook.Open(strFilePath);
Cells cells = workbook.Worksheets[0].Cells;
//4表示从第5行开始,0代表第一行
dtExcel = cells.ExportDataTableAsString(4, 0, cells.MaxDataRow + 1, cells.MaxColumn+1, true);//showTitle
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return dtExcel;
}