You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
excelImport/Source/ExcelImprot/MainWindow.cs

354 lines
14 KiB

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;
}
}
}