c#讀取excel內容內容示例分享。本站提示廣大學習愛好者:(c#讀取excel內容內容示例分享)文章只能為提供參考,不一定能成為您想要的結果。以下是c#讀取excel內容內容示例分享正文
1、Excel 需是.xls 格局
2、添加援用Microsoft.Office.Interop.Excel.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Diagnostics;
namespace ReadExcel
{
class Program
{
static void Main(string[] args)
{
string fileName = @"D:\TransferPlant\111.xls";
DataTable dt = ExcelToDataSet(fileName);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Console.WriteLine(dt.Rows[i][0].ToString());
}
}
}
static public DataTable ExcelToDataSet(string filename)
{
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "+filename+";Extended Properties=Excel 8.0";
OleDbConnection conn = new OleDbConnection(strCon);
conn.Open();
//前往Excel的架構,包含各個sheet表的稱號,類型,創立時光和修正時光等
DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
//包括excel中表名的字符串數組
string[] strTableNames = new string[dtSheetName.Rows.Count];
for (int k = 0; k < dtSheetName.Rows.Count; k++)
{
strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
}
OleDbDataAdapter myCommand = null;
DataTable dt = new DataTable();
//從指定的注解查詢數據,可先把一切注解列出來供用戶選擇
string strExcel = "select * from [" + strTableNames[0] + "]";
myCommand = new OleDbDataAdapter(strExcel, strCon);
myCommand.Fill(dt);
return dt;
}
}
}