WinForm 프로젝트 개발 중 Excel 용법 인 스 턴 스 분석

7457 단어 WinFormExcel
실제 프로젝트 의 개발 과정 에서 관련 된 EXCEL 은 비교적 복잡 하고 열 에 계산 공식 이 있 기 때문에 읽 기 에 큰 어려움 을 가 져 왔 다.예 를 들 어 Myxls,NPOI,IExcel DataReader 등 무료 제3자 dll 을 시도 한 적 이 있다.마지막 으로 OLEDB 형식 으로 읽 고 x64 운영 체제 에 문제 가 있다.그러나 작은 기술 로 해결 할 수 있 습 니 다.링크 주 소 를 참고 할 수 있 습 니 다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;//      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 를 정상적으로 읽 을 수 있 습 니 다.
코드 실행 효 과 는 다음 그림 과 같 습 니 다.

좋은 웹페이지 즐겨찾기