上面分别是Excel文档的内容和读取结果;
奉上C#源代码:
using System; using System.Data; using System.Data.OleDb; namespace ReadExcel { class ReadExcel { static void Main() { DataSet dataset = ReadExcel.ExcelToDS(@"D: est1.xls"); DataTable table = dataset.Tables["table1"]; for (int i = 0; i < table.Rows.Count; i++) { DataRow row = table.Rows[i]; /* 默认会把Excel的第一行作为列名,当HDR=NO时则以序号取数,或者以F1,F2,F3……的方式取数 * 当HDR=NO时则以序号取数,或者以F1,F2,F3……的方式取数 * 例如:row[0],row[1],row[2]或者row[F1],row[F2],row[F3] */ string country = Convert.ToString(row["国家"]); string nationality = Convert.ToString(row["民族"]); Console.WriteLine(country + " " + nationality); } Console.ReadKey(); } public static DataSet ExcelToDS(string Path) { string filename = System.IO.Path.GetFileName(Path);//文件名 string extension = System.IO.Path.GetExtension(Path);//扩展名 “.xlsx” string strConn = string.Empty; if (extension == "xls") { //默认以Excel文档的第一行作为列名,如果不需要则设置:HDR=NO //strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties='Excel 8.0;HDR=NO'"; strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;"; } else { //strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + Path + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'"; strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + Path + ";Extended Properties='Excel 12.0; IMEX=1'"; } OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); string strExcel = ""; OleDbDataAdapter myCommand = null; DataSet ds = null; strExcel = "select * from [sheet1$]"; myCommand = new OleDbDataAdapter(strExcel, strConn); ds = new DataSet(); myCommand.Fill(ds, "table1"); return ds; } } }