excel import

master
syneffort 3 years ago
parent 65a4481043
commit 34dd1094d6
  1. BIN
      Resource/Graphicloads-Filetype-Excel-xls.ico
  2. 22
      Source/ExcelImprot.sln
  3. 6
      Source/ExcelImprot/App.config
  4. 108
      Source/ExcelImprot/Dialog/StartupDialog.Designer.cs
  5. 131
      Source/ExcelImprot/Dialog/StartupDialog.cs
  6. 3157
      Source/ExcelImprot/Dialog/StartupDialog.resx
  7. 108
      Source/ExcelImprot/ExcelImprot.csproj
  8. BIN
      Source/ExcelImprot/Graphicloads-Filetype-Excel-xls.ico
  9. 747
      Source/ExcelImprot/LExcelHandler.cs
  10. 43
      Source/ExcelImprot/MainController.cs
  11. 238
      Source/ExcelImprot/MainWindow.Designer.cs
  12. 354
      Source/ExcelImprot/MainWindow.cs
  13. 2976
      Source/ExcelImprot/MainWindow.resx
  14. 23
      Source/ExcelImprot/Program.cs
  15. 36
      Source/ExcelImprot/Properties/AssemblyInfo.cs
  16. 71
      Source/ExcelImprot/Properties/Resources.Designer.cs
  17. 117
      Source/ExcelImprot/Properties/Resources.resx
  18. 30
      Source/ExcelImprot/Properties/Settings.Designer.cs
  19. 7
      Source/ExcelImprot/Properties/Settings.settings

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 KiB

@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExcelImprot", "ExcelImprot\ExcelImprot.csproj", "{0357039F-0BBB-449E-86FB-EE0433203A53}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0357039F-0BBB-449E-86FB-EE0433203A53}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0357039F-0BBB-449E-86FB-EE0433203A53}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0357039F-0BBB-449E-86FB-EE0433203A53}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0357039F-0BBB-449E-86FB-EE0433203A53}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

@ -0,0 +1,108 @@
namespace ExcelImprot.Dialog
{
partial class StartupDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(StartupDialog));
this.prgBar = new System.Windows.Forms.ProgressBar();
this.txtCurrentMessage = new System.Windows.Forms.TextBox();
this.bgwInitializer = new System.ComponentModel.BackgroundWorker();
this.panel1 = new System.Windows.Forms.Panel();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// prgBar
//
this.prgBar.Cursor = System.Windows.Forms.Cursors.AppStarting;
this.prgBar.Location = new System.Drawing.Point(-2, 39);
this.prgBar.Name = "prgBar";
this.prgBar.Size = new System.Drawing.Size(487, 9);
this.prgBar.TabIndex = 11;
this.prgBar.Value = 100;
//
// txtCurrentMessage
//
this.txtCurrentMessage.BackColor = System.Drawing.Color.White;
this.txtCurrentMessage.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.txtCurrentMessage.Cursor = System.Windows.Forms.Cursors.Arrow;
this.txtCurrentMessage.Enabled = false;
this.txtCurrentMessage.Font = new System.Drawing.Font("맑은 고딕", 9.75F, System.Drawing.FontStyle.Bold);
this.txtCurrentMessage.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
this.txtCurrentMessage.Location = new System.Drawing.Point(-2, 13);
this.txtCurrentMessage.Name = "txtCurrentMessage";
this.txtCurrentMessage.ReadOnly = true;
this.txtCurrentMessage.Size = new System.Drawing.Size(487, 18);
this.txtCurrentMessage.TabIndex = 10;
this.txtCurrentMessage.TabStop = false;
this.txtCurrentMessage.Text = "프로그램 구동을 준비합니다.";
this.txtCurrentMessage.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// bgwInitializer
//
this.bgwInitializer.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bgwInitializer_DoWork);
this.bgwInitializer.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bgwInitializer_RunWorkerCompleted);
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.White;
this.panel1.Controls.Add(this.txtCurrentMessage);
this.panel1.Controls.Add(this.prgBar);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(1, 1);
this.panel1.Name = "panel1";
this.panel1.Padding = new System.Windows.Forms.Padding(1);
this.panel1.Size = new System.Drawing.Size(479, 65);
this.panel1.TabIndex = 12;
//
// StartupDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(232)))), ((int)(((byte)(171)))), ((int)(((byte)(145)))));
this.ClientSize = new System.Drawing.Size(481, 67);
this.Controls.Add(this.panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "StartupDialog";
this.Padding = new System.Windows.Forms.Padding(1);
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "StartupDialog";
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ProgressBar prgBar;
private System.Windows.Forms.TextBox txtCurrentMessage;
private System.ComponentModel.BackgroundWorker bgwInitializer;
private System.Windows.Forms.Panel panel1;
}
}

@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ExcelImprot.Dialog
{
public partial class StartupDialog : Form
{
private delegate void PropertyDelegate(Control objMother, Control objControl, EnableType eType, bool bValue);
private delegate void MessageDelegate(string strMessage);
private delegate void Startup_Act();
private MainWindow _wndMain;
bool _bControllerInitialized = true;
public StartupDialog()
{
InitializeComponent();
InitVariables();
}
private void InitVariables()
{
ShowMessage("프로그램 구동을 준비합니다.");
prgBar.Style = ProgressBarStyle.Marquee;
prgBar.MarqueeAnimationSpeed = 30;
bgwInitializer.WorkerSupportsCancellation = true;
bgwInitializer.RunWorkerAsync();
}
private void Initialize()
{
_bControllerInitialized = MainController.GetInstance().Initialize();
//Application.Idle += FinishingDialog;
}
private void FinishingDialog()
{
//Application.Idle -= FinishingDialog;
if (!_bControllerInitialized)
{
ShowMessage("프로그램 구동준비에 실패하였습니다. 프로그램을 종료합니다.");
Exit();
return;
}
ShowMessage("프로그램 구동 준비가 완료되었습니다. 프로그램을 시작합니다.");
EnableProperty(this, this, EnableType.Visible, false);
_wndMain = new MainWindow();
EnableProperty(this, _wndMain, EnableType.Visible, true);
}
private void EnableProperty(Control objMother, Control objControl, EnableType eType, bool bValue)
{
if (objMother.InvokeRequired)
{
PropertyDelegate objDelegate = new PropertyDelegate(EnableProperty);
objMother.Invoke(objDelegate, new object[] { objMother, objControl, eType, bValue });
}
else
{
switch (eType)
{
case EnableType.Enabled:
objControl.Enabled = bValue;
break;
case EnableType.Visible:
objControl.Visible = bValue;
break;
default:
break;
}
}
}
private void ShowMessage(string strMessage)
{
if (InvokeRequired)
{
MessageDelegate objDelegate = new MessageDelegate(ShowMessage);
Invoke(objDelegate, strMessage);
}
else
{
txtCurrentMessage.Text = strMessage;
Application.DoEvents();
}
}
private void Exit()
{
if (MainController.GetInstance().OpenedExcel != null)
MainController.GetInstance().OpenedExcel.CloseOpenedExcel();
Application.ExitThread();
Application.Exit();
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
private void bgwInitializer_DoWork(object sender, DoWorkEventArgs e)
{
Initialize();
}
private void bgwInitializer_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
FinishingDialog();
}
}
public enum EnableType
{
Visible,
Enabled
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,108 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{0357039F-0BBB-449E-86FB-EE0433203A53}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ExcelImprot</RootNamespace>
<AssemblyName>ExcelImprot</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>Graphicloads-Filetype-Excel-xls.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Office.Interop.Excel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Dialog\StartupDialog.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="Dialog\StartupDialog.Designer.cs">
<DependentUpon>StartupDialog.cs</DependentUpon>
</Compile>
<Compile Include="MainController.cs" />
<Compile Include="MainWindow.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="MainWindow.Designer.cs">
<DependentUpon>MainWindow.cs</DependentUpon>
</Compile>
<Compile Include="LExcelHandler.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<EmbeddedResource Include="Dialog\StartupDialog.resx">
<DependentUpon>StartupDialog.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="MainWindow.resx">
<DependentUpon>MainWindow.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<Content Include="Graphicloads-Filetype-Excel-xls.ico" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 KiB

@ -0,0 +1,747 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Data;
using System.Drawing;
namespace ExcelImprot
{
public class LExcelHandler
{
private bool _bDisposed = false;
private SafeHandle _objSafeHandler = new SafeFileHandle(IntPtr.Zero, true);
private bool _bIsActive = false;
private Excel.Application _objApp = null;
private Excel.Workbooks _objWorkbooks = null;
private Excel.Workbook _objWorkbook = null;
private Excel.Sheets _objSheets = null;
private Excel.Worksheet _objWorksheet = null;
private Excel.Range _objRange = null;
/// <summary>
/// 객체 생성자입니다.
/// </summary>
/// <param name="bPrepareApplication">사전 엑셀 어플리케이션 생성여부입니다.</param>
public LExcelHandler(bool bPrepareApplication)
{
if (bPrepareApplication)
{
try
{
_objApp = new Excel.Application();
_objWorkbooks = _objApp.Workbooks;
}
catch (Exception ex)
{
throw ex;
}
}
}
/// <summary>
/// 지정된 경로의 엑셀파일을 읽어 DataTable형으로 반환합니다.
/// </summary>
/// <param name="strFilePath">엑셀파일 경로</param>
/// <returns>반환된 DataTable형 객체</returns>
/// <summary>
/// 지정된 경로의 엑셀파일을 읽어 DataTable형으로 반환합니다.
/// </summary>
/// <param name="strFilePath">엑셀파일 경로</param>
/// <param name="iWorkSheetNumber">읽을 시트 번호입니다.</param>
/// <param name="bIngnoreReadOnlyRecommended">읽기전용 경고를 무시할지 여부입니다.</param>
/// <returns>반환된 DataTable형 객체</returns>
public DataTable ReadAsDataTableFromOpenedExcel(string strFilePath, int iWorkSheetNumber = 1, bool bIngnoreReadOnlyRecommended = false)
{
if (_objApp == null)
{
try
{
_objApp = new Excel.Application();
_objWorkbooks = _objApp.Workbooks;
}
catch (Exception ex)
{
throw ex;
}
}
DataTable objDataTable = new DataTable();
try
{
_objWorkbook = _objApp.Workbooks.Open(strFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, bIngnoreReadOnlyRecommended);
_objSheets = _objWorkbook.Worksheets;
_objWorksheet = _objSheets.get_Item(iWorkSheetNumber) as Excel.Worksheet;
_objRange = _objWorksheet.UsedRange;
//Excel.Range objRange = objWorksheet.Range[objWorksheet.Cells[2, 1], objWorksheet.Cells[5, 1]];
object[,] objData = _objRange.Value;
for (int i = 0; i < objData.GetLength(1); i++)
{
objDataTable.Columns.Add(DecToAlphabet(i));
}
for (int r = 1; r <= objData.GetLength(0); r++)
{
DataRow objRow = objDataTable.NewRow();
for (int c = 1; c <= objData.GetLength(1); c++)
{
object objValue = objData[r, c];
string strValue = "";
if (objValue != null)
strValue = objData[r, c].ToString();
objRow[c - 1] = strValue;
}
objDataTable.Rows.Add(objRow);
}
_objWorkbook.Saved = true;
_objWorkbook.Close(true);
}
catch (Exception ex)
{
throw ex;
}
return objDataTable;
}
/// <summary>
/// 지정된 경로의 엑셀파일을 읽어 Object 2차원 배열로 반환합니다.
/// </summary>
/// <param name="strFilePath">파일경로</param>
/// <param name="iWorkSheetNumber">워크시트번호</param>
/// <param name="bIngnoreReadOnlyRecommended">오류 무시 여부</param>
/// <returns>엑셀로부터 읽어진 2차원 배열, 오류시 NULL을 반환합니다.</returns>
public object[,] ReadAsArrayFromOpenedExcel(string strFilePath, int iWorkSheetNumber = 1, bool bIngnoreReadOnlyRecommended = false)
{
if (_objApp == null)
{
try
{
_objApp = new Excel.Application();
_objWorkbooks = _objApp.Workbooks;
}
catch (Exception ex)
{
throw ex;
}
}
object[,] objData = null;
try
{
_objWorkbook = _objWorkbooks.Open(strFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, bIngnoreReadOnlyRecommended);
_objSheets = _objWorkbook.Worksheets;
_objWorksheet = _objSheets.get_Item(iWorkSheetNumber) as Excel.Worksheet;
_objRange = _objWorksheet.UsedRange;
objData = _objRange.Value;
_objWorkbook.Saved = true;
_objWorkbook.Close(true);
}
catch (Exception ex)
{
throw ex;
}
return objData;
}
public void CloseOpenedExcel()
{
try
{
if (_objApp != null)
_objApp.Quit();
}
catch (Exception ex)
{
throw ex;
}
finally
{
LExcelHandler.ReleaseExcelObject(_objRange);
LExcelHandler.ReleaseExcelObject(_objWorksheet);
LExcelHandler.ReleaseExcelObject(_objSheets);
LExcelHandler.ReleaseExcelObject(_objWorkbook);
LExcelHandler.ReleaseExcelObject(_objWorkbooks);
LExcelHandler.ReleaseExcelObject(_objApp);
_objApp = null;
}
}
/// <summary>
/// 지정된 경로의 엑셀파일을 읽어 Object 2차원 배열로 반환합니다.
/// </summary>
/// <param name="strFilePath">파일 경로</param>
/// <param name="iWorkSheetNumber">워크 시트 번호</param>
/// <param name="bIngnoreReadOnlyRecommended">오류 무시 여부</param>
/// <returns>엑셀로 부터 읽어진 2차원 배열, 오류 시 NULL을 반환합니다.</returns>
public static object[,] ReadAsArray(string strFilePath, int iWorkSheetNumber = 1, bool bIngnoreReadOnlyRecommended = false)
{
Excel.Application objExcelApp = null;
Excel.Workbooks objWorkbooks = null;
Excel.Workbook objSelectedWorkbook = null;
Excel.Sheets objSheets = null;
Excel.Worksheet objSelectedWorksheet = null;
Excel.Range objSelectedRange = null;
object[,] objData = null;
try
{
objExcelApp = new Excel.Application();
objWorkbooks = objExcelApp.Workbooks;
objSelectedWorkbook = objWorkbooks.Open(strFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, bIngnoreReadOnlyRecommended);
objSheets = objSelectedWorkbook.Worksheets;
objSelectedWorksheet = objSheets.get_Item(iWorkSheetNumber) as Excel.Worksheet;
objSelectedRange = objSelectedWorksheet.UsedRange;
objData = objSelectedRange.Value;
objSelectedWorkbook.Saved = true;
objSelectedWorkbook.Close(true);
objExcelApp.Quit();
}
catch (Exception ex)
{
throw ex;
}
finally
{
LExcelHandler.ReleaseExcelObject(objSelectedRange);
LExcelHandler.ReleaseExcelObject(objSelectedWorksheet);
LExcelHandler.ReleaseExcelObject(objSheets);
LExcelHandler.ReleaseExcelObject(objSelectedWorkbook);
LExcelHandler.ReleaseExcelObject(objWorkbooks);
LExcelHandler.ReleaseExcelObject(objExcelApp);
objExcelApp = null;
}
return objData;
}
/// <summary>
/// 지정된 경로의 엑셀파일을 읽어 DataTable형으로 반환합니다.
/// </summary>
/// <param name="strFilePath">엑셀파일 경로</param>
/// <returns>반환된 DataTable형 객체</returns>
public static DataTable ReadAsDataTable(string strFilePath, int iWorkSheetNumber = 1, bool bIngnoreReadOnlyRecommended = false)
{
Excel.Application objApp = null;
Excel.Workbooks objWorkbooks = null;
Excel.Workbook objWorkbook = null;
Excel.Sheets objSheets = null;
Excel.Worksheet objWorksheet = null;
Excel.Range objTargetRange = null;
DataTable objDataTable = new DataTable();
try
{
objApp = new Excel.Application();
objWorkbook = objApp.Workbooks.Open(strFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, bIngnoreReadOnlyRecommended);
objWorksheet = objWorkbook.Worksheets.get_Item(iWorkSheetNumber) as Excel.Worksheet;
objTargetRange = objWorksheet.UsedRange;
//Excel.Range objRange = objWorksheet.Range[objWorksheet.Cells[2, 1], objWorksheet.Cells[5, 1]];
object[,] objData = objTargetRange.Value;
for (int i = 0; i < objData.GetLength(1); i++)
{
objDataTable.Columns.Add(DecToAlphabet(i));
}
for (int r = 1; r <= objData.GetLength(0); r++)
{
DataRow objRow = objDataTable.NewRow();
for (int c = 1; c <= objData.GetLength(1); c++)
{
object objValue = objData[r, c];
string strValue = "";
if (objValue != null)
strValue = objData[r, c].ToString();
objRow[c - 1] = strValue;
}
objDataTable.Rows.Add(objRow);
}
objWorkbook.Close(true);
objApp.Quit();
}
catch (Exception ex)
{
throw ex;
}
finally
{
LExcelHandler.ReleaseExcelObject(objTargetRange);
LExcelHandler.ReleaseExcelObject(objWorksheet);
LExcelHandler.ReleaseExcelObject(objSheets);
LExcelHandler.ReleaseExcelObject(objWorkbook);
LExcelHandler.ReleaseExcelObject(objWorkbooks);
LExcelHandler.ReleaseExcelObject(objApp);
objApp = null;
}
return objDataTable;
}
/// <summary>
/// 입력된 DataTable형 데이터를 지정된 경로의 엑셀파일로 저장합니다.
/// </summary>
/// <param name="objDataTable">저장할 DataTable 객체</param>
/// <param name="strFilePath">저장할 파일 경로</param>
/// <param name="bWriteHeader">헤더를 포함할지 여부입니다.</param>
/// <returns>LReturnMessage형 결과 값으로 함수 실행이 성공하였으면 객체 내 IsOK 변수에 true 반환하며 실패하였다면 false를 반환합니다. false 시, 오류 메세지가 객체 내 ExceptionMessage에 저장됩니다.</returns>
public bool Save(DataTable objDataTable, string strFilePath, bool bWriteHeader)
{
if (_objApp == null)
{
try
{
_objApp = new Excel.Application();
_objWorkbooks = _objApp.Workbooks;
}
catch (Exception ex)
{
throw ex;
}
}
try
{
_objWorkbook = _objWorkbooks.Add();
_objWorksheet = _objWorkbook.Worksheets.get_Item(1) as Excel.Worksheet;
if (bWriteHeader)
{
// 헤더 저장
for (int i = 0; i < objDataTable.Columns.Count; i++)
{
string strHeader = "";
if (objDataTable.Columns[i].ColumnName != null)
strHeader = objDataTable.Columns[i].ColumnName;
_objWorksheet.Cells[1, i + 1] = strHeader;
}
for (int r = 0; r < objDataTable.Rows.Count; r++)
{
for (int c = 0; c < objDataTable.Columns.Count; c++)
{
_objWorksheet.Cells[r + 2, c + 1] = objDataTable.Rows[r][c];
}
}
}
else
{
for (int r = 0; r < objDataTable.Rows.Count; r++)
{
for (int c = 0; c < objDataTable.Columns.Count; c++)
{
_objWorksheet.Cells[r + 1, c + 1] = objDataTable.Rows[r][c];
}
}
}
_objWorkbook.SaveAs(strFilePath, Excel.XlFileFormat.xlOpenXMLWorkbook);
_objWorkbook.Saved = true;
_objWorkbook.Close(true);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
#region Excel Drawing
/// <summary>
/// 현재 워크북을 저장하고 닫습니다..
/// </summary>
/// <param name="strFilePath">저장 경로</param>
/// <returns>처리 여부</returns>
public bool SaveCurrentWorkbook(string strFilePath)
{
try
{
_objWorkbook.SaveAs(strFilePath, Excel.XlFileFormat.xlOpenXMLWorkbook);
_objWorkbook.Saved = true;
_objWorkbook.Close(true);
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 엑셀에 입력한 데이터 테이블 정보를 입력합니다.
/// </summary>
/// <param name="objDataTable"></param>
/// <returns>처리 여부</returns>
public bool SetData(DataTable objDataTable, bool bWriteHeader = true)
{
if (_objApp == null)
{
try
{
_objApp = new Excel.Application();
_objWorkbooks = _objApp.Workbooks;
}
catch (Exception ex)
{
return false;
}
}
try
{
_objWorkbook = _objWorkbooks.Add();
_objWorksheet = _objWorkbook.Worksheets.get_Item(1) as Excel.Worksheet;
if (bWriteHeader)
{
// 헤더 저장
for (int i = 0; i < objDataTable.Columns.Count; i++)
{
string strHeader = "";
if (objDataTable.Columns[i].ColumnName != null)
strHeader = objDataTable.Columns[i].ColumnName;
_objWorksheet.Cells[1, i + 1] = strHeader;
}
for (int r = 0; r < objDataTable.Rows.Count; r++)
{
for (int c = 0; c < objDataTable.Columns.Count; c++)
{
_objWorksheet.Cells[r + 2, c + 1] = objDataTable.Rows[r][c];
}
}
}
else
{
for (int r = 0; r < objDataTable.Rows.Count; r++)
{
for (int c = 0; c < objDataTable.Columns.Count; c++)
{
_objWorksheet.Cells[r + 1, c + 1] = objDataTable.Rows[r][c];
}
}
}
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 사용된 전체 셀을 선택합니다.
/// </summary>
/// <returns></returns>
public Excel.Range SelectUsedRange()
{
_objRange = _objWorksheet.UsedRange;
return _objRange;
}
/// <summary>
/// 단일 셀을 선택합니다.
/// </summary>
/// <param name="strCell">셀 주소</param>
/// <returns>선택한 셀 역역</returns>
public Excel.Range SelectCell(string strCell)
{
_objRange = _objWorksheet.Range[strCell, Type.Missing];
return _objRange;
}
/// <summary>
/// 단일 셀을 선택합니다.
/// </summary>
/// <param name="iRow">셀 행</param>
/// <param name="iCol">셀 열</param>
/// <returns>선택한 셀 영역</returns>
public Excel.Range SelectCell(int iRow, int iCol)
{
string strCell = CellAddress(iRow, iCol);
_objRange = _objWorksheet.Range[strCell, Type.Missing];
return _objRange;
}
/// <summary>
/// 다중 셀을 선택합니다.
/// </summary>
/// <param name="strStartCell">시작 셀 주소</param>
/// <param name="strEndCell">종료 셀 주소</param>
/// <returns>선택한 셀 영역</returns>
public Excel.Range SelectCell(string strStartCell, string strEndCell)
{
_objRange = _objWorksheet.Range[strStartCell, strEndCell];
return _objRange;
}
/// <summary>
/// 다중 셀을 선택합니다.
/// </summary>
/// <param name="iStartRow">시작 셀 행</param>
/// <param name="iStartCol">시작 셀 열</param>
/// <param name="iEndRow">끝 셀 행</param>
/// <param name="iEndCol">끝 셀 열</param>
/// <returns></returns>
public Excel.Range SelectCell(int iStartRow, int iStartCol, int iEndRow, int iEndCol)
{
string strStartCell = CellAddress(iStartRow, iStartCol);
string strEndCell = CellAddress(iEndRow, iEndCol);
_objRange = _objWorksheet.Range[strStartCell, strEndCell];
return _objRange;
}
/// <summary>
/// 선택된 셀 영역의 색상을 지정합니다.
/// </summary>
/// <param name="objColor">지정할 색상</param>
/// <returns>처리 여부</returns>
public bool SetColor(Color objColor)
{
if (_objRange == null)
return false;
_objRange.Interior.Color = ColorTranslator.ToOle(objColor);
return true;
}
/// <summary>
/// 선택된 셀 영역의 컬럼을 자동맞춤 합니다.
/// </summary>
/// <returns>처리 여부</returns>
public bool SetColumnWidth()
{
if (_objRange == null)
return false;
_objRange.Columns.AutoFit();
return true;
}
/// <summary>
/// 선택된 셀 영역의 컬럼의 폭을 설정합니다.
/// </summary>
/// <param name="dWidth">폭</param>
/// <returns>처리 여부</returns>
public bool SetColumnWidth(double dWidth)
{
if (_objRange == null)
return false;
_objRange.ColumnWidth = dWidth;
return true;
}
/// <summary>
/// 선택된 셀 영역을 병합합니다.
/// </summary>
/// <returns>처리 여부</returns>
public bool SetMerge()
{
if (_objRange == null)
return false;
_objRange.Merge(true);
return true;
}
/// <summary>
/// 선택된 셀 영역의 폰트 사이즈를 설정합니다.
/// </summary>
/// <param name="iSize">폰트 사이즈</param>
/// <returns>처리 여부</returns>
public bool SetSize(int iSize)
{
if (_objRange == null)
return false;
_objRange.Font.Size = iSize;
return true;
}
/// <summary>
/// 선택된 셀 영역을 볼드 처리합니다.
/// </summary>
/// <returns>처리 여부</returns>
public bool SetBold()
{
if (_objRange == null)
return false;
_objRange.Font.Bold = true;
return true;
}
/// <summary>
/// 선택된 셀 영역을 가운데 정렬 처리 합니다.
/// </summary>
/// <returns>처리 여부</returns>
public bool SetCenterAlign()
{
if (_objRange == null)
return false;
_objRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
return true;
}
/// <summary>
/// 선택한 셀 영역의 테두리를 설정합니다.
/// </summary>
/// <param name="bOutline">외곽선</param>
/// <param name="bHorizontal">내부 세로선</param>
/// <param name="bVertical">내부 가로선</param>
/// <returns>처리 여부</returns>
public bool SetBorder(bool bOutline = true, bool bHorizontal = true, bool bVertical = true)
{
if (_objRange == null)
return false;
if (bOutline)
_objRange.BorderAround2(Type.Missing, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic);
if (bHorizontal)
_objRange.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
if (bVertical)
_objRange.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
return true;
}
/// <summary>
/// 엑셀상 셀 주소를 반환합니다.
/// </summary>
/// <param name="iRow">열 번호</param>
/// <param name="iCol">행 번호</param>
/// <returns>셀 주소</returns>
public static string CellAddress(int iRow, int iCol)
{
string strReturn = DecToAlphabet(iCol - 1);
strReturn += iRow;
return strReturn;
}
#endregion
private static bool ReleaseExcelObject(object objObject)
{
try
{
if (objObject != null)
{
Marshal.ReleaseComObject(objObject);
objObject = null;
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
objObject = null;
throw ex;
}
finally
{
GC.Collect();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool bDisposing)
{
if (_bDisposed)
return;
if (bDisposing)
_objSafeHandler.Dispose();
_bDisposed = true;
}
/// <summary>
/// 정수형 숫자를 문자열 형태로 변환하여 반환합니다.
/// 반환되는 문자열 형태는 엑셀의 컬럼명 형태입니다.
/// </summary>
/// <param name="iDec">변환할 int형</param>
/// <returns>변환된 문자열</returns>
public static string DecToAlphabet(int iDec)
{
int iRest;
string alphabet;
byte[] asciiA = Encoding.ASCII.GetBytes("A");
iRest = iDec % 26;
asciiA[0] += (byte)iRest;
alphabet = Encoding.ASCII.GetString(asciiA);
iDec = iDec / 26 - 1;
if (iDec > -1)
{
alphabet = alphabet.Insert(0, DecToAlphabet(iDec));
}
return alphabet;
}
}
}

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelImprot
{
public class MainController
{
private static MainController _objMySelf;
private LExcelHandler _objExcelHander;
private MainController()
{
}
public static MainController GetInstance()
{
if (_objMySelf == null)
_objMySelf = new MainController();
return _objMySelf;
}
public bool Initialize()
{
_objExcelHander = new LExcelHandler(true);
if (_objExcelHander == null)
return false;
return true;
}
public LExcelHandler OpenedExcel
{
get { return _objExcelHander; }
}
}
}

@ -0,0 +1,238 @@
namespace ExcelImprot
{
partial class MainWindow
{
/// <summary>
/// 필수 디자이너 변수입니다.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 사용 중인 모든 리소스를 정리합니다.
/// </summary>
/// <param name="disposing">관리되는 리소스를 삭제해야 하면 true이고, 그렇지 않으면 false입니다.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form 디자이너에서 생성한 코드
/// <summary>
/// 디자이너 지원에 필요한 메서드입니다.
/// 이 메서드의 내용을 코드 편집기로 수정하지 마십시오.
/// </summary>
private void InitializeComponent()
{
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainWindow));
this.mnuMainStrip = new System.Windows.Forms.MenuStrip();
this.mnuFile = new System.Windows.Forms.ToolStripMenuItem();
this.mnuNew = new System.Windows.Forms.ToolStripMenuItem();
this.mnuOpen = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.mnuSave = new System.Windows.Forms.ToolStripMenuItem();
this.mnuExcelSave = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.mnuExit = new System.Windows.Forms.ToolStripMenuItem();
this.mnuOption = new System.Windows.Forms.ToolStripMenuItem();
this.mnuLargeData = new System.Windows.Forms.ToolStripMenuItem();
this.grdData = new System.Windows.Forms.DataGridView();
this.stsMainStrip = new System.Windows.Forms.StatusStrip();
this.objProgress = new System.Windows.Forms.ToolStripProgressBar();
this.pnlMain = new System.Windows.Forms.TableLayoutPanel();
this.mnuMainStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.grdData)).BeginInit();
this.stsMainStrip.SuspendLayout();
this.pnlMain.SuspendLayout();
this.SuspendLayout();
//
// mnuMainStrip
//
this.mnuMainStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuFile,
this.mnuOption});
this.mnuMainStrip.Location = new System.Drawing.Point(0, 0);
this.mnuMainStrip.Name = "mnuMainStrip";
this.mnuMainStrip.Size = new System.Drawing.Size(722, 24);
this.mnuMainStrip.TabIndex = 0;
this.mnuMainStrip.Text = "menuStrip1";
//
// mnuFile
//
this.mnuFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuNew,
this.mnuOpen,
this.toolStripMenuItem1,
this.mnuSave,
this.mnuExcelSave,
this.toolStripMenuItem2,
this.mnuExit});
this.mnuFile.Name = "mnuFile";
this.mnuFile.Size = new System.Drawing.Size(57, 20);
this.mnuFile.Text = "파일(&F)";
//
// mnuNew
//
this.mnuNew.Name = "mnuNew";
this.mnuNew.Size = new System.Drawing.Size(155, 22);
this.mnuNew.Text = "새로 만들기(&N)";
this.mnuNew.Click += new System.EventHandler(this.mnuNew_Click);
//
// mnuOpen
//
this.mnuOpen.Name = "mnuOpen";
this.mnuOpen.Size = new System.Drawing.Size(155, 22);
this.mnuOpen.Text = "열기(&O)";
this.mnuOpen.Click += new System.EventHandler(this.mnuOpen_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(152, 6);
//
// mnuSave
//
this.mnuSave.Name = "mnuSave";
this.mnuSave.Size = new System.Drawing.Size(155, 22);
this.mnuSave.Text = "csv 저장(&S)";
this.mnuSave.Click += new System.EventHandler(this.mnuSave_Click);
//
// mnuExcelSave
//
this.mnuExcelSave.Name = "mnuExcelSave";
this.mnuExcelSave.Size = new System.Drawing.Size(155, 22);
this.mnuExcelSave.Text = "엑셀 저장(&S)";
this.mnuExcelSave.Visible = false;
this.mnuExcelSave.Click += new System.EventHandler(this.mnuExcelSave_Click);
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(152, 6);
//
// mnuExit
//
this.mnuExit.Name = "mnuExit";
this.mnuExit.Size = new System.Drawing.Size(155, 22);
this.mnuExit.Text = "닫기(&X)";
this.mnuExit.Click += new System.EventHandler(this.mnuExit_Click);
//
// mnuOption
//
this.mnuOption.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuLargeData});
this.mnuOption.Name = "mnuOption";
this.mnuOption.Size = new System.Drawing.Size(60, 20);
this.mnuOption.Text = "옵션(&O)";
//
// mnuLargeData
//
this.mnuLargeData.Name = "mnuLargeData";
this.mnuLargeData.Size = new System.Drawing.Size(198, 22);
this.mnuLargeData.Text = "대용량 처리 (비활성중)";
this.mnuLargeData.Click += new System.EventHandler(this.mnuLargeData_Click);
//
// grdData
//
this.grdData.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.grdData.BackgroundColor = System.Drawing.Color.White;
this.grdData.BorderStyle = System.Windows.Forms.BorderStyle.None;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle1.Font = new System.Drawing.Font("맑은 고딕", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(129)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.grdData.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.grdData.Dock = System.Windows.Forms.DockStyle.Fill;
this.grdData.Location = new System.Drawing.Point(3, 3);
this.grdData.MultiSelect = false;
this.grdData.Name = "grdData";
this.grdData.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.grdData.RowTemplate.Height = 23;
this.grdData.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect;
this.grdData.Size = new System.Drawing.Size(716, 666);
this.grdData.TabIndex = 11;
this.grdData.ColumnAdded += new System.Windows.Forms.DataGridViewColumnEventHandler(this.grdData_ColumnAdded);
this.grdData.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.grdData_RowPostPaint);
//
// stsMainStrip
//
this.stsMainStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.objProgress});
this.stsMainStrip.Location = new System.Drawing.Point(0, 696);
this.stsMainStrip.Name = "stsMainStrip";
this.stsMainStrip.Size = new System.Drawing.Size(722, 22);
this.stsMainStrip.TabIndex = 12;
this.stsMainStrip.Text = "statusStrip1";
//
// objProgress
//
this.objProgress.Name = "objProgress";
this.objProgress.Size = new System.Drawing.Size(100, 16);
this.objProgress.Style = System.Windows.Forms.ProgressBarStyle.Marquee;
//
// pnlMain
//
this.pnlMain.ColumnCount = 1;
this.pnlMain.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.pnlMain.Controls.Add(this.grdData, 0, 0);
this.pnlMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnlMain.Location = new System.Drawing.Point(0, 24);
this.pnlMain.Name = "pnlMain";
this.pnlMain.RowCount = 1;
this.pnlMain.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.pnlMain.Size = new System.Drawing.Size(722, 672);
this.pnlMain.TabIndex = 13;
//
// MainWindow
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(722, 718);
this.Controls.Add(this.pnlMain);
this.Controls.Add(this.stsMainStrip);
this.Controls.Add(this.mnuMainStrip);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.mnuMainStrip;
this.Name = "MainWindow";
this.Text = "ExcelImport";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainWindow_FormClosing);
this.mnuMainStrip.ResumeLayout(false);
this.mnuMainStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.grdData)).EndInit();
this.stsMainStrip.ResumeLayout(false);
this.stsMainStrip.PerformLayout();
this.pnlMain.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip mnuMainStrip;
private System.Windows.Forms.ToolStripMenuItem mnuFile;
private System.Windows.Forms.ToolStripMenuItem mnuNew;
private System.Windows.Forms.ToolStripMenuItem mnuOpen;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem mnuSave;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem mnuExit;
private System.Windows.Forms.DataGridView grdData;
private System.Windows.Forms.StatusStrip stsMainStrip;
private System.Windows.Forms.ToolStripProgressBar objProgress;
private System.Windows.Forms.TableLayoutPanel pnlMain;
private System.Windows.Forms.ToolStripMenuItem mnuExcelSave;
private System.Windows.Forms.ToolStripMenuItem mnuOption;
private System.Windows.Forms.ToolStripMenuItem mnuLargeData;
}
}

@ -0,0 +1,354 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ExcelImprot
{
public partial class MainWindow : Form
{
private DataTable _objReadData;
private delegate void ProgressbarDelegate(bool bEnable);
private delegate void DataSourceDelegate(DataTable objData);
private delegate void ColumnAutosizeDelegate();
private string _strFileNameCandidate;
private bool _bLargeData = false;
public MainWindow()
{
InitializeComponent();
InitVariables();
typeof(DataGridView).InvokeMember("DoubleBuffered", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.SetProperty, null, grdData, new object[] { true });
grdData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
private void InitVariables()
{
_objReadData = new DataTable();
grdData.DataSource = null;
GC.Collect();
OnProgress(false);
}
private void OnProgress(bool bEnable)
{
if (InvokeRequired)
{
ProgressbarDelegate objProgressbarDelegate = new ProgressbarDelegate(OnProgress);
Invoke(objProgressbarDelegate, bEnable);
}
else
{
mnuMainStrip.Enabled = !bEnable;
grdData.Enabled = !bEnable;
if (bEnable)
{
objProgress.Style = ProgressBarStyle.Marquee;
objProgress.MarqueeAnimationSpeed = 30;
}
else
{
objProgress.MarqueeAnimationSpeed = 0;
objProgress.Value = 0;
objProgress.Style = ProgressBarStyle.Blocks;
}
}
}
private void GridDataBind(DataTable objDataTable)
{
if (InvokeRequired)
{
DataSourceDelegate objDataSourceDelegate = new DataSourceDelegate(GridDataBind);
Invoke(objDataSourceDelegate, objDataTable);
}
else
{
grdData.DataSource = null;
grdData.DataSource = objDataTable;
}
}
private void ReadExcel(object objPath)
{
OnProgress(true);
_objReadData = new DataTable();
_objReadData = MainController.GetInstance().OpenedExcel.ReadAsDataTableFromOpenedExcel(objPath.ToString(), 1, true);
if (_objReadData != null)
GridDataBind(_objReadData);
OnProgress(false);
}
private void SaveExcel(object objPath)
{
OnProgress(true);
StringBuilder objStringBuilder = new StringBuilder();
foreach (DataGridViewRow objThisRow in grdData.Rows)
{
if (objThisRow.Index == grdData.Rows.Count - 1)
continue;
List<string> objRowValues = new List<string>();
for (int i = 0; i < objThisRow.Cells.Count; i++)
{
object objThisValue = objThisRow.Cells[i].Value;
if (objThisValue == null)
{
objRowValues.Add("");
}
else
{
string strValue = objThisValue.ToString();
if (strValue.Contains(','))
objRowValues.Add(string.Format("\"{0}\"", strValue));
else
objRowValues.Add(strValue);
}
}
objStringBuilder.AppendLine(string.Join(",", objRowValues.ToArray()));
}
try
{
File.WriteAllText(objPath.ToString(), objStringBuilder.ToString(), Encoding.UTF8);
}
catch (Exception ex)
{
MessageBox.Show("다음과 같은 이유로 저장에 실패하였습니다." + Environment.NewLine + ex.Message, "저장 실패", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
OnProgress(false);
}
private void mnuNew_Click(object sender, EventArgs e)
{
DialogResult objDlgResult = MessageBox.Show("정말 새로 시작하시겠습니까?", "알림", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (objDlgResult != DialogResult.Yes)
return;
_strFileNameCandidate = "";
InitVariables();
}
private void mnuOpen_Click(object sender, EventArgs e)
{
OpenFileDialog objDlg = new OpenFileDialog();
objDlg.Filter = "Excel files (*.xls,*xlsx)|*.xls;*xlsx|All files (*.*)|*.*";
if (objDlg.ShowDialog() == DialogResult.OK)
{
string strPath = objDlg.FileName;
_strFileNameCandidate = Path.GetFileNameWithoutExtension(strPath);
if (!File.Exists(strPath))
{
MessageBox.Show("선택한 파일이 존재하지 않습니다.", "에러", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Thread objReadThread = new Thread(new ParameterizedThreadStart(ReadExcel));
objReadThread.Start(strPath);
}
}
private void mnuSave_Click(object sender, EventArgs e)
{
SaveFileDialog objDlg = new SaveFileDialog();
objDlg.Filter = ".csv 파일|*.csv|모든파일|*.*";
objDlg.FileName = _strFileNameCandidate;
if (objDlg.ShowDialog() == DialogResult.OK)
{
string strPath = objDlg.FileName;
Thread objSaveThread = new Thread(new ParameterizedThreadStart(SaveExcel));
objSaveThread.Start(strPath);
}
}
private void mnuExit_Click(object sender, EventArgs e)
{
if (MainController.GetInstance().OpenedExcel != null)
MainController.GetInstance().OpenedExcel.CloseOpenedExcel();
Application.ExitThread();
Application.Exit();
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
private void grdData_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
DataGridView objGrid = sender as DataGridView;
int iRowShowIndex = e.RowIndex + 1;
StringFormat objFormat = new StringFormat()
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
Rectangle objHeaderRect = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grdData.RowHeadersWidth, e.RowBounds.Height);
e.Graphics.DrawString(iRowShowIndex.ToString(), this.Font, SystemBrushes.ControlText, objHeaderRect, objFormat);
}
private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
{
mnuExit_Click(sender, e);
}
private void mnuExcelSave_Click(object sender, EventArgs e)
{
//DataTable objDataTable = new DataTable();
//List<DataRow> objDataRowList = new List<DataRow>();
//// 헤더생성
//objDataTable.Columns.Add("판매오더");
//objDataTable.Columns.Add("품목");
//objDataTable.Columns.Add("타입");
//objDataTable.Columns.Add("품번");
//objDataTable.Columns.Add("품명");
//objDataTable.Columns.Add("고객명");
//objDataTable.Columns.Add("납기일");
//int iCurrentIdx = 6;
//Dictionary<string, int> objColumnIdx = new Dictionary<string, int>(); // Key : 공정코드, Value : 데이터테이블 인덱스
//foreach (KeyValuePair<Guid, LMProcess> objThisProcessMaster in _objPlanSimulator.DataSource.ProcessMasters)
//{
// iCurrentIdx++;
// string strProcessCode = objThisProcessMaster.Value.Code;
// objDataTable.Columns.Add(strProcessCode);
// objColumnIdx.Add(strProcessCode, iCurrentIdx);
//}
//// 본문 채우기
//foreach (string strThisOrderKey in uclSimulationResultByOrder.OrderKeys)
//{
// LMOrder objThisOrder = uclSimulationResultByOrder.SelectOrder(strThisOrderKey);
// if (objThisOrder == null)
// continue;
// DataRow objDataRow = objDataTable.NewRow();
// objDataRow[0] = objThisOrder.SalesOrderID;
// objDataRow[1] = objThisOrder.SalesOrderSub;
// if (_objPlanSimulator.DataSource.Products.ContainsKey(objThisOrder.ProductID))
// objDataRow[2] = _objPlanSimulator.DataSource.Products[objThisOrder.ProductID].ProductGroupName;
// else
// objDataRow[2] = objThisOrder.ModelType;
// objDataRow[3] = objThisOrder.ProductID;
// objDataRow[4] = objThisOrder.ProductName;
// objDataRow[5] = objThisOrder.Customer;
// objDataRow[6] = objThisOrder.DeliveryDate.ToString("yyyy-MM-dd");
// for (int i = 7; i < 7 + objColumnIdx.Count; i++)
// {
// objDataRow[i] = "없음";
// }
// List<SimResultByOrderBindingClass> objSelectedOrderData = uclSimulationResultByOrder.SelectedOrderData(strThisOrderKey);
// foreach (SimResultByOrderBindingClass objData in objSelectedOrderData)
// {
// if (!objColumnIdx.ContainsKey(objData.ProcessCode))
// continue;
// int iColIdx = objColumnIdx[objData.ProcessCode];
// if (objData.EndTime == null || objData.EndTime == "" || objData.EndTime == "-")
// objDataRow[iColIdx] = "진행중";
// else
// objDataRow[iColIdx] = objData.EndTime;
// }
// objDataTable.Rows.Add(objDataRow);
//}
//// 엑셀 객체로 정리 후 저장
//try
//{
// int iDataWidth = objDataTable.Columns.Count;
// int iDataHeight = objDataTable.Rows.Count + 1;
// LExcelHandler objExcel = LIMMController.GetInstance().OpenedExcel;
// // 데이터 입력
// objExcel.SetData(objDataTable, true);
// // 헤더 셀 정리
// //objExcel.SelectCell(LExcelHandler.CellAddress(1, 1), LExcelHandler.CellAddress(1, iDataWidth));
// objExcel.SelectCell(1, 1, 1, iDataWidth);
// objExcel.SetBold();
// objExcel.SetColor(Color.LightGray);
// // 내용 색상 처리
// for (int iRow = 2; iRow <= iDataHeight; iRow++)
// {
// for (int iCol = 7; iCol <= iDataWidth; iCol++)
// {
// if (objExcel.SelectCell(LExcelHandler.CellAddress(iRow, iCol)).Value2 == null)
// continue;
// string strValue = objExcel.SelectCell(LExcelHandler.CellAddress(iRow, iCol)).Value2.ToString();
// switch (strValue)
// {
// case "없음":
// break;
// case "진행중":
// objExcel.SetColor(objLightYellow);
// break;
// default:
// objExcel.SetColor(objLightGreen);
// break;
// }
// }
// }
// // 사용한 셀 선택
// //objExcel.SelectCell(LExcelHandler.CellAddress(1, 1), LExcelHandler.CellAddress(iDataHeight, iDataWidth));
// objExcel.SelectCell(1, 1, iDataHeight, iDataWidth);
// // 컬럼 자동맞춤
// objExcel.SetColumnWidth();
// // 내용 가운데 정렬
// objExcel.SetCenterAlign();
// // 전체 테두리
// objExcel.SetBorder();
// // 공정코드 컬럼 너비 조정
// //objExcel.SelectCell(LExcelHandler.CellAddress(1, 7), LExcelHandler.CellAddress(iDataHeight, iDataWidth));
// objExcel.SelectCell(1, 7, iDataHeight, iDataWidth);
// objExcel.SetColumnWidth(17);
// objExcel.SaveCurrentWorkbook(strFilePath);
//}
//catch (Exception ex)
//{
// MessageBox.Show("다음과 같은 이유로 결과 요약 리포트 저장에 실패하였습니다." + Environment.NewLine + ex.Message, "저장 실패", MessageBoxButtons.OK, MessageBoxIcon.Error);
//}
}
private void mnuLargeData_Click(object sender, EventArgs e)
{
_bLargeData = !_bLargeData;
if (_bLargeData)
mnuLargeData.Text = "대용량 처리(활성중)";
else
mnuLargeData.Text = "대용량 처리(비활성중)";
}
private void grdData_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
if (_bLargeData)
e.Column.FillWeight = 1;
}
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,23 @@
using ExcelImprot.Dialog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ExcelImprot
{
static class Program
{
/// <summary>
/// 해당 응용 프로그램의 주 진입점입니다.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new StartupDialog());
}
}
}

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 어셈블리의 일반 정보는 다음 특성 집합을 통해 제어됩니다.
// 어셈블리와 관련된 정보를 수정하려면
// 이 특성 값을 변경하십시오.
[assembly: AssemblyTitle("ExcelImprot")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ExcelImprot")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에
// 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면
// 해당 형식에 대해 ComVisible 특성을 true로 설정하십시오.
[assembly: ComVisible(false)]
// 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다.
[assembly: Guid("a61f2e35-6e15-4979-876a-6e85b190143e")]
// 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다.
//
// 주 버전
// 부 버전
// 빌드 번호
// 수정 버전
//
// 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 버전이 자동으로
// 지정되도록 할 수 있습니다.
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 이 코드는 도구를 사용하여 생성되었습니다.
// 런타임 버전:4.0.30319.42000
//
// 파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면
// 이러한 변경 내용이 손실됩니다.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ExcelImprot.Properties
{
/// <summary>
/// 지역화된 문자열 등을 찾기 위한 강력한 형식의 리소스 클래스입니다.
/// </summary>
// 이 클래스는 ResGen 또는 Visual Studio와 같은 도구를 통해 StronglyTypedResourceBuilder
// 클래스에서 자동으로 생성되었습니다.
// 멤버를 추가하거나 제거하려면 .ResX 파일을 편집한 다음 /str 옵션을 사용하여
// ResGen을 다시 실행하거나 VS 프로젝트를 다시 빌드하십시오.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 이 클래스에서 사용하는 캐시된 ResourceManager 인스턴스를 반환합니다.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ExcelImprot.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 이 강력한 형식의 리소스 클래스를 사용하여 모든 리소스 조회에 대한 현재 스레드의 CurrentUICulture
/// 속성을 재정의합니다.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ExcelImprot.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
Loading…
Cancel
Save