WinForm項(xiàng)目開發(fā)中Excel用法實(shí)例解析
在實(shí)際項(xiàng)目的開發(fā)過程中,所涉及的EXCEL往往會(huì)比較復(fù)雜,并且列中還會(huì)帶有一些計(jì)算公式,這就給讀取帶來了很大的困難,曾經(jīng)嘗試過一些免費(fèi)的第三方dll,譬如Myxls,NPOI,IExcelDataReader都會(huì)出現(xiàn)一些問題,最后采用OLEDB形式讀取,再x64操作系統(tǒng)上有點(diǎn)問題,不過采用小技巧即可解決,可以參考鏈接地址:http://ellisweb.net/2010/01/connecting-to-excel-and-access-files-using-net-on-a-64-bit-server/
封裝代碼如下:
namespace DBUtilHelpV2
{
public class OLEDBExcelToolV2
{
static readonly string xls = ".xls";
static readonly string xlsx = ".xlsx";
string _ExcelExtension = string.Empty;//后綴
string _ExcelPath = string.Empty;//路徑
string _ExcelConnectString = string.Empty;//鏈接字符串
static bool _X64Version = false;//是否強(qiáng)制使用x64鏈接字符串,即xlsx形式
public OLEDBExcelToolV2(string excelPath, bool x64Version)
{
if (string.IsNullOrEmpty(excelPath))
throw new ArgumentNullException("excelPath");
if (!File.Exists(excelPath))
throw new ArgumentException("excelPath");
string _excelExtension = Path.GetExtension(excelPath);
_ExcelExtension = _excelExtension.ToLower();
_ExcelPath = excelPath;
_X64Version = x64Version;
_ExcelConnectString = BuilderConnectionString();
}
/// <summary>
/// 創(chuàng)建鏈接字符串
/// </summary>
/// <returns></returns>
private string BuilderConnectionString()
{
Dictionary<string, string> _connectionParameter = new Dictionary<string, string>();
if (!_ExcelExtension.Equals(xlsx) && !_ExcelExtension.Equals(xls))
{
throw new ArgumentException("excelPath");
}
if (!_X64Version)
{
if (_ExcelExtension.Equals(xlsx))
{
// XLSX - Excel 2007, 2010, 2012, 2013
_connectionParameter["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
_connectionParameter["Extended Properties"] = "'Excel 12.0 XML;IMEX=1'";
}
else if (_ExcelExtension.Equals(xls))
{
// XLS - Excel 2003 and Older
_connectionParameter["Provider"] = "Microsoft.Jet.OLEDB.4.0";
_connectionParameter["Extended Properties"] = "'Excel 8.0;IMEX=1'";
}
}
else
{
_connectionParameter["Provider"] = "Microsoft.ACE.OLEDB.12.0;";
_connectionParameter["Extended Properties"] = "'Excel 12.0 XML;IMEX=1'";
}
_connectionParameter["Data Source"] = _ExcelPath;
StringBuilder _connectionString = new StringBuilder();
foreach (KeyValuePair<string, string> parameter in _connectionParameter)
{
_connectionString.Append(parameter.Key);
_connectionString.Append('=');
_connectionString.Append(parameter.Value);
_connectionString.Append(';');
}
return _connectionString.ToString();
}
/// <summary>
/// Excel操作
/// DELETE不支持
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public int ExecuteNonQuery(string sql)
{
int _affectedRows = -1;
using (OleDbConnection sqlcon = new OleDbConnection(_ExcelConnectString))
{
try
{
sqlcon.Open();
using (OleDbCommand sqlcmd = new OleDbCommand(sql, sqlcon))
{
_affectedRows = sqlcmd.ExecuteNonQuery();
}
}
catch (Exception)
{
return -1;
}
}
return _affectedRows;
}
/// <summary>
/// Excel操作
///獲取EXCEL內(nèi)sheet集合
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public string[] GetExcelSheetNames()
{
DataTable _schemaTable = null;
using (OleDbConnection sqlcon = new OleDbConnection(_ExcelConnectString))
{
try
{
sqlcon.Open();
_schemaTable = sqlcon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] _excelSheets = new String[_schemaTable.Rows.Count];
int i = 0;
foreach (DataRow row in _schemaTable.Rows)
{
_excelSheets[i] = row["TABLE_NAME"].ToString().Trim();
i++;
}
return _excelSheets;
}
catch (Exception)
{
return null;
}
finally
{
if (_schemaTable != null)
{
_schemaTable.Dispose();
}
}
}
}
/// <summary>
/// 讀取sheet
/// eg:select * from [Sheet1$]
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public DataTable ExecuteDataTable(string sql)
{
using (OleDbConnection sqlcon = new OleDbConnection(_ExcelConnectString))
{
try
{
using (OleDbCommand sqlcmd = new OleDbCommand(sql, sqlcon))
{
using (OleDbDataAdapter sqldap = new OleDbDataAdapter(sqlcmd))
{
DataTable _dtResult = new DataTable();
sqldap.Fill(_dtResult);
return _dtResult;
}
}
}
catch (Exception)
{
return null;
}
}
}
/// <summary>
/// 獲取excel所有sheet數(shù)據(jù)
/// </summary>
/// <returns>DataSet</returns>
public DataSet ExecuteDataSet()
{
DataSet _excelDb = null;
using (OleDbConnection sqlcon = new OleDbConnection(_ExcelConnectString))
{
try
{
sqlcon.Open();
DataTable _schemaTable = sqlcon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (_schemaTable != null)
{
int i = 0;
_excelDb = new DataSet();
foreach (DataRow row in _schemaTable.Rows)
{
string _sheetName = row["TABLE_NAME"].ToString().Trim();
string _sql = string.Format("select * from [{0}]", _sheetName);
using (OleDbCommand sqlcmd = new OleDbCommand(_sql, sqlcon))
{
using (OleDbDataAdapter sqldap = new OleDbDataAdapter(sqlcmd))
{
DataTable _dtResult = new DataTable();
_dtResult.TableName = _sheetName;
sqldap.Fill(_dtResult);
_excelDb.Tables.Add(_dtResult);
}
}
i++;
}
}
}
catch (Exception)
{
return null;
}
}
return _excelDb;
}
}
}
代碼使用方法如下:
/// <summary>
/// 合并EXCEL數(shù)據(jù)
/// </summary>
/// <param name="_excelPath">excel路徑</param>
private void HandleMergeExcel(string _excelPath)
{
if (!string.IsNullOrEmpty(_excelPath))
{
OLEDBExcelToolV2 _excelHelper = new OLEDBExcelToolV2(_excelPath, true);
DataSet _excelSource = _excelHelper.ExecuteDataSet();
HandleExcelSource(_excelSource);
}
}
若在x64操作系統(tǒng),將第二個(gè)參數(shù)設(shè)置true,并且按照AccessDatabaseEngine_X64.exe即可正常讀取
代碼運(yùn)行效果如下圖所示:

- WinForm導(dǎo)出文件為Word、Excel、文本文件的方法
- winform導(dǎo)出dataviewgrid數(shù)據(jù)為excel的方法
- C# WinForm導(dǎo)出Excel方法介紹
- .Net中導(dǎo)出數(shù)據(jù)到Excel(asp.net和winform程序中)
- C#數(shù)據(jù)導(dǎo)入/導(dǎo)出Excel文件及winForm導(dǎo)出Execl總結(jié)
- C#控制Excel Sheet使其自適應(yīng)頁寬與列寬的方法
- C#使用oledb導(dǎo)出數(shù)據(jù)到excel的方法
- C#.net編程創(chuàng)建Access文件和Excel文件的方法詳解
- C#的Excel導(dǎo)入、導(dǎo)出
- C#使用winform簡(jiǎn)單導(dǎo)出Excel的方法
相關(guān)文章
c#獲取季度時(shí)間實(shí)例代碼(季度的第一天)
這篇文章主要介紹了c#獲取季度時(shí)間:季度的第一天、季度的最后一天等功能,大家參考使用吧2013-12-12
winform異型不規(guī)則界面設(shè)計(jì)的實(shí)現(xiàn)方法
這篇文章主要介紹了winform異型不規(guī)則界面設(shè)計(jì)的實(shí)現(xiàn)方法,具有不錯(cuò)的實(shí)用價(jià)值,需要的朋友可以參考下2014-08-08
Microsoft Expression Web 簡(jiǎn)體中文正式版 官方下載地址
Microsoft Expression Web 簡(jiǎn)體中文正式版 官方下載地址...2007-07-07
C#實(shí)現(xiàn)帶進(jìn)度條的ListView
這篇文章主要介紹了C#實(shí)現(xiàn)帶進(jìn)度條的ListView 的相關(guān)資料,需要的朋友可以參考下2016-02-02
C#基于Socket的TCP通信實(shí)現(xiàn)聊天室案例
這篇文章主要為大家詳細(xì)介紹了C#基于Socket的TCP通信實(shí)現(xiàn)聊天室案例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02

