c#讀取excel內容內容示例分享
更新時間:2014年03月06日 12:06:00 作者:
這篇文章主要介紹了c#讀取excel內容內容示例,要求Excel需是.xls格式,需要的朋友可以參考下
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表的名稱,類型,創(chuàng)建時間和修改時間等
DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
//包含excel中表名的字符串數(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;
}
}
}
相關文章
C#創(chuàng)建Windows Service(Windows 服務)的方法步驟
本文介紹了如何用C#創(chuàng)建、安裝、啟動、監(jiān)控、卸載簡單的Windows Service 的內容步驟和注意事項,具有一定的參考價值,感興趣的可以了解一下2023-11-11C#根據(jù)excel數(shù)據(jù)繪制坐標圖的方法
這篇文章主要為大家詳細介紹了C#根據(jù)excel數(shù)據(jù)繪制坐標圖的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02