c#讀取excel內(nèi)容內(nèi)容示例分享
更新時(shí)間:2014年03月06日 12:06:00 作者:
這篇文章主要介紹了c#讀取excel內(nèi)容內(nèi)容示例,要求Excel需是.xls格式,需要的朋友可以參考下
1、Excel 需是.xls 格式
2、添加引用Microsoft.Office.Interop.Excel.dll
復(fù)制代碼 代碼如下:
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的架構(gòu),包括各個(gè)sheet表的名稱,類型,創(chuàng)建時(shí)間和修改時(shí)間等
DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
//包含excel中表名的字符串?dāng)?shù)組
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();
//從指定的表明查詢數(shù)據(jù),可先把所有表明列出來供用戶選擇
string strExcel = "select * from [" + strTableNames[0] + "]";
myCommand = new OleDbDataAdapter(strExcel, strCon);
myCommand.Fill(dt);
return dt;
}
}
}
您可能感興趣的文章:
相關(guān)文章
WinForm自定義函數(shù)FindControl實(shí)現(xiàn)按名稱查找控件
這篇文章主要介紹了WinForm自定義函數(shù)FindControl實(shí)現(xiàn)按名稱查找控件,需要的朋友可以參考下2014-08-08
C#控制臺程序?qū)崿F(xiàn)開啟、關(guān)閉SQLServer服務(wù)的代碼分享
這篇文章主要介紹了C#控制臺程序?qū)崿F(xiàn)開啟、關(guān)閉SQLServer服務(wù)的代碼分享,需要的朋友可以參考下2014-05-05
帶著問題讀CLR via C#(筆記一)CLR的執(zhí)行模型
CLR (Common Language Runtime) 是一個(gè)可以由多種編程語言使用的“運(yùn)行時(shí)”。2013-04-04
淺談C#中HttpWebRequest與HttpWebResponse的使用方法
本篇文章主要介紹了淺談C#中HttpWebRequest與HttpWebResponse的使用方法,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01

