C#读取Excel

2017-03-07  本文已影响0人  红定义

using System;

using System.Data;

using System.Data.OleDb;

namespace ClientExcelTableManager

{

class Program

{

public static string tablePath = @"E:\ExchangeItem.xlsx";

static void Main(string[] args)

{

DataSet _dataset = ToDataTable(tablePath);

if (_dataset != null)

{

for (int i = 0; i < _dataset.Tables.Count; i++)

{

Console.WriteLine(_dataset.Tables[i].TableName + " / row: " + _dataset.Tables[i].Rows.Count + "  / column: " + _dataset.Tables[i].Columns.Count);

for (int j = 0; j < _dataset.Tables[i].Rows.Count; j++)

{

for (int k = 0; k < _dataset.Tables[i].Rows[j].ItemArray.Length; k++)

{

Console.Write(_dataset.Tables[i].Rows[j].ItemArray[k].ToString() + "|");

}

Console.WriteLine("\r");

}

}

}

Console.ReadLine();

}

public static DataSet ToDataTable(string filePath)

{

string connStr = "";

string fileType = System.IO.Path.GetExtension(filePath);

if (string.IsNullOrEmpty(fileType)) return null;

if (fileType == ".xls")

{

connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1\"";

}

else

{

connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1\"";

}

string sql_F = "select * from [{0}]";

OleDbConnection conn = null;

OleDbDataAdapter da = null;

DataTable dtSheetName = null;

DataSet ds = new DataSet();

try

{

conn = new OleDbConnection(connStr);

conn.Open();

string SheetName = "";

dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

da = new OleDbDataAdapter();

for (int i = 0; i < dtSheetName.Rows.Count; i++)

{

SheetName = (string)dtSheetName.Rows[i]["TABLE_NAME"];

da.SelectCommand = new OleDbCommand(String.Format(sql_F, SheetName), conn);

DataSet dsItem = new DataSet();

da.Fill(dsItem, SheetName);

ds.Tables.Add(dsItem.Tables[0].Copy());

}

}

catch (Exception ex)

{

Console.WriteLine("Exception! " + ex);

}

finally

{

if (conn.State == ConnectionState.Open)

{

conn.Close();

da.Dispose();

conn.Dispose();

}

}

return ds;

}

}

}

上一篇下一篇

猜你喜欢

热点阅读