WinForm 프로젝트 개발 중 Excel 용법 인 스 턴 스 분석
패키지 코드 는 다음 과 같 습 니 다:
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;// 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>
///
/// </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 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
/// </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
/// </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 운영 체제 에서 두 번 째 매개 변 수 를 true 로 설정 하고 AccessDatabaseEngineX64.exe 를 정상적으로 읽 을 수 있 습 니 다.코드 실행 효 과 는 다음 그림 과 같 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
C# Excel 템플릿 내보내기(Word 등)프로젝트에서 Excel, Word, pdf 등 템플릿 내보내기를 자주 사용해야 합니다. 다음은 자신이 정리한 간단한 버전의 템플릿 내보내기입니다. 복잡한 내보내기와 유사합니다. 조금만 수정하면 됩니다.다음 내보내기 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.