public class ExcelService
{
MessageUtil msgUtil = new MessageUtil();
#region Member Values
private Excel.Application xlApp = null;
private Excel.Workbook xlWorkBook = null;
private Excel.Worksheet xlWorkSheet = null;
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
public ExcelService()
{
// 생성자;
}
#endregion
#region Excel Upload
public string ExcelOpen()
{
try
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.Title = "File Open";
openFile.Filter = "Excel Files|*.xls;*.xlsx|All Files|*.*";
openFile.RestoreDirectory = true;
if (openFile.ShowDialog() != DialogResult.OK) return null;
return openFile.FileName;
}
catch
{
return null;
}
}
/// <summary>
/// Excel Uploading
/// </summary>
/// <param name="OriColName"> ColumnName </param>
/// <returns> Excel DataSet </returns>
public DataSet ExcelUpload(string[] OriColName)
{
string strFilePath = null;
strFilePath = this.ExcelOpen();
if (string.IsNullOrEmpty(strFilePath)) return null;
try
{
this.xlApp = new Excel.Application();
this.xlWorkBook = xlApp.Workbooks.Open(strFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
this.xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets.get_Item(1);
this.xlApp.Visible = false;
this.xlApp.DisplayAlerts = false;
}
catch (Exception ex)
{
throw ex;
return null;
}
OleDbConnection ODCon = null;
OleDbCommand ODCmd = null;
OleDbDataAdapter ODAdt = null;
DataSet DS = null;
try
{
ODCon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePath + ";Extended Properties='Excel 8.0;HDR=YES'");
ODCmd = new OleDbCommand("SELECT * FROM [" + xlWorkSheet.Name + "$]", ODCon);
ODAdt = new OleDbDataAdapter();
ODAdt.SelectCommand = ODCmd;
DS = new DataSet();
ODAdt.Fill(DS);
ODCon.Close();
if (OriColName.Count() != 0)
{
for (int iLoop = 0; iLoop < OriColName.Count(); iLoop++)
{
DS.Tables[0].Columns[iLoop].Caption = DS.Tables[0].Columns[iLoop].ColumnName;
DS.Tables[0].Columns[iLoop].ColumnName = OriColName[iLoop];
}
}
return DS;
}
catch (Exception ex)
{
throw ex;
return null;
}
}
#endregion
#region Excel Memory Kill
/// <summary>
/// Excel Process Memory Kill
/// </summary>
public void ExcelDispose()
{
try
{
xlApp.Quit();
Process[] proc = Process.GetProcessesByName("EXCEL");
foreach (Process p in proc)
{
if (p.MainWindowTitle == "") p.Kill();
}
xlApp = null;
}
catch
{
return;
}
}
#endregion
}
'Study > Programming' 카테고리의 다른 글
C# 파일 입출력 예제 (0) | 2011.02.27 |
---|---|
C# 엑셀 & CSV OleDb로 가져오기 읽어오기 (0) | 2011.02.15 |
C# 울트라그리드 멀티헤더 (0) | 2011.02.14 |
C# 키 유효성 검사 숫자만 입력 (0) | 2011.01.25 |
C# panel 마우스클릭 이동 (0) | 2011.01.12 |