프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

hytos / ID2.Manager / ExcelAddin / ID2ManagerImport / DataImport.cs @ 32b2f84d

이력 | 보기 | 이력해설 | 다운로드 (12.7 KB)

1 43ceb5b3 taeseongkim
using SqlConnectionDialog;
2
using System;
3
using System.Collections.Generic;
4
using System.Linq;
5
using System.Text;
6
using System.Threading.Tasks;
7
using System.Data.SqlClient;
8
using Microsoft.Office.Interop.Excel;
9
using System.Windows.Forms;
10
using System.Drawing;
11
using System.IO;
12
using System.IO.Compression;
13
14
namespace ID2ManagerImport
15
{
16
    public static class DataManager
17
    {
18
        static string tableName = "ImportExcel";
19
20
        public static string ConnectionDialog()
21
        {
22
            var factory = new ConnectionStringFactory();
23
            var str = factory.OpenDialog();
24
25
            return str;
26
        }
27
28
29
        public static bool CreateTabile(string connectionString)
30
        {
31
            bool result = false;
32
33
            try
34
            {
35
                using (SqlConnection connection = new SqlConnection(connectionString))
36
                {
37
                    connection.Open();
38
39
                    string checkTableQuery = $"SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '{tableName}'";
40
41
                    // 쿼리 실행하여 테이블 존재 여부 확인
42
                    SqlCommand checkTableCommand = new SqlCommand(checkTableQuery, connection);
43
44
                    int tableCount = (int)checkTableCommand.ExecuteScalar();
45
46
                    if (tableCount == 0)
47
                    {
48
                        // CREATE TABLE 문 작성
49
                        string createTableQuery = $"CREATE TABLE {tableName} ( "
50
                                    + " FILE_NAME VARCHAR(MAX),"
51
                                    + " WORKSHEET_NAME VARCHAR(MAX),"
52
                                    + " COUMMN_INDEX INT,"
53
                                    + " ROW_INDEX INT,"
54
                                    + " VALUE VARCHAR(MAX),"
55
                                    + " TopLeftCell VARCHAR(MAX),"
56
                                    + " OBJECT_TYPE INT"
57
                                  + " )";
58
59
                        // CREATE TABLE 쿼리 실행
60
                        SqlCommand createTableCommand = new SqlCommand(createTableQuery, connection);
61
                        createTableCommand.ExecuteNonQuery();
62
63
                        connection.Close();
64
                    }
65
                    
66
                    result = true;
67
                }
68
            }
69
            catch (Exception)
70
            {
71
                throw;
72
            }
73
            return result;
74
        }
75
76
        public static void DeleteData(SqlConnection connection,string FileName, string worksheetName)
77
        {
78
            
79
                string delQuery = $"DELETE FROM {tableName} WHERE FILE_NAME = '{FileName}' AND WORKSHEET_NAME = '{worksheetName}'";
80
81
                // SQL 쿼리 실행
82
                SqlCommand command = new SqlCommand(delQuery, connection);
83
                command.ExecuteNonQuery();
84
        }
85
86
        public static bool Import(string FileName, Microsoft.Office.Interop.Excel.Worksheet worksheet)
87
        {
88
            bool result = true;
89
90
            try
91
            {
92
                var connectionStr = ConnectionDialog();
93
94
                if (connectionStr != null)
95
                {
96 0688f998 taeseongkim
                    //Globals.ThisAddIn.Application.Cursor = Microsoft.Office.Interop.Excel.XlMousePointer.xlWait;
97
98 43ceb5b3 taeseongkim
                    if (CreateTabile(connectionStr))
99
                    {
100
101
                        using (SqlConnection connection = new SqlConnection(connectionStr))
102
                        {
103
                            connection.Open();
104
105
                            DeleteData(connection, FileName, worksheet.Name);
106
107
                            Range range = worksheet.UsedRange;
108
109
                            // 행 반복
110
                            for (int row = 1; row <= range.Rows.Count; row++)
111
                            {
112
                                // 열 반복
113
                                for (int column = 1; column <= range.Columns.Count; column++)
114
                                {
115
                                    string cellAddress = range.Cells[row, column].Address;
116
                                    var cellValue = range.Cells[row, column].Value;
117
                                    //Range cell = range.Cells[row, column];
118
                                    //XlCellType cellType = cell.Cells[row, column].CellType;
119
                                    //// 현재 셀 값 가져오기
120
                                    //string cellValue = cell.Cells[row, column].Value2.ToString();
121
                                    if (cellValue != null)
122
                                    {
123
                                        // SQL INSERT 쿼리 작성
124
                                        string query = $"INSERT INTO {tableName} (FILE_NAME,WORKSHEET_NAME,COUMMN_INDEX,ROW_INDEX,VALUE,TopLeftCell,OBJECT_TYPE) "
125
                                                     + $" VALUES ('{FileName}','{worksheet.Name}',{column},{row},'{cellValue}','{cellAddress}',0)";
126
127
                                        // SQL 쿼리 실행
128
                                        SqlCommand command = new SqlCommand(query, connection);
129
                                        command.ExecuteNonQuery();
130
                                    }
131
                                }
132
                            }
133
134
                            ImportImage(connection, FileName, worksheet);
135
136
                            connection.Close();
137
                            result = true;
138
                        }
139
                    }
140
                }
141
            }
142
            catch (Exception)
143
            {
144
145
                throw;
146
            }
147
148
            return result;
149
        }
150
151
        private static int GetColumnIndex(string CellAddress)
152
        {
153
            int columnIndex = 0;
154
155
            if (CellAddress.TrimStart('$').Split('$').Length > 0)
156
            {
157
                string columnAddress = CellAddress.TrimStart('$').Split('$')[0];
158
159
                foreach (char c in columnAddress)
160
                {
161
                    columnIndex = columnIndex * 26 + (int)c - 64;
162
                }
163
            }
164
165
            return columnIndex;
166
        }
167
168
        private static int GetRowIndex(string CellAddress)
169
        {
170
            int RowIndex = 0;
171
172
            if (CellAddress.TrimStart('$').Split('$').Length > 1)
173
            {
174
                string columnAddress = CellAddress.TrimStart('$').Split('$')[1];
175
                RowIndex = Convert.ToInt32(columnAddress);
176
            }
177
178
            return RowIndex;
179
        }
180
181
182
        public static bool ImportImage(SqlConnection connection, string FILE_NAME, Worksheet worksheet)
183
        {
184
            bool result = true;
185
186
            try
187
            {
188
189
                const Microsoft.Office.Core.MsoShapeType pictureShapeType = Microsoft.Office.Core.MsoShapeType.msoPicture;
190
191
                string query = $"INSERT INTO {tableName} (FILE_NAME,WORKSHEET_NAME,COUMMN_INDEX,ROW_INDEX,TopLeftCell,VALUE,OBJECT_TYPE) "
192
                                        + $" VALUES (@FileName,@worksheetName,@ColumnIndex,@RowIndex,@TopLeftCell,@cellValue,@ObjectType)";
193
194
                List<Microsoft.Office.Interop.Excel.Shape> shapes = new List<Shape>();
195
196
                foreach (Shape shape in worksheet.Shapes)
197
                {
198
                    shapes.Add(shape);
199
                }
200
201
                foreach (Shape shape in shapes)
202
                {
203
                    if (shape.Type == pictureShapeType)
204
                    {
205
                        string location = shape.TopLeftCell.Address; // 이미지의 위치 정보
206
                        string base64String = null;
207
208
                        try
209
                        {
210
                            float originalHeight = shape.Height;
211
                            float originalWidth = shape.Width;
212
                            shape.ScaleWidth(1.0f, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoScaleFrom.msoScaleFromTopLeft);
213
214
                            // 이미지를 가져올 Shape이 그림인 경우 처리
215
                            shape.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlBitmap);
216
217
                                if (Clipboard.ContainsImage())
218
                                {
219
                                    // 클립보드에서 이미지 가져오기
220
                                    using (Image clipboardImage = Clipboard.GetImage())
221
                                    {
222
                                        // 이미지 크기를 원래 크기로 되돌리기
223
224
                                        // 이미지를 byte 배열로 변환
225
                                        byte[] imageBytes;
226
                                        using (MemoryStream ms = new MemoryStream())
227
                                        {
228
                                            clipboardImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
229
                                            imageBytes = ms.ToArray();
230
231
                                            // 이미지를 Base64 문자열로 변환
232
                                            base64String = CompressString(Convert.ToBase64String(imageBytes));
233
                                            imageBytes = null;
234
                                        }
235
                                    }
236
237
238
                                    shape.ScaleWidth(originalWidth / shape.Width, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoScaleFrom.msoScaleFromTopLeft);
239
                                    Clipboard.Clear();
240
                                }
241
                            }
242
                            catch (Exception ex)
243
                            {
244
                                System.Diagnostics.Debug.WriteLine(ex);
245
                            }
246
247
                        // 이미지를 MSSQL에 저장
248
                        SqlCommand insertCommand = new SqlCommand(query, connection);
249
                        insertCommand.Parameters.AddWithValue("@FileName", FILE_NAME);
250
                        insertCommand.Parameters.AddWithValue("@worksheetName", worksheet.Name);
251
                        insertCommand.Parameters.AddWithValue("@ColumnIndex", GetColumnIndex(location));
252
                        insertCommand.Parameters.AddWithValue("@RowIndex", GetRowIndex(location));
253
                        insertCommand.Parameters.AddWithValue("@TopLeftCell", location);
254
                        insertCommand.Parameters.AddWithValue("@cellValue", base64String);
255
                        insertCommand.Parameters.AddWithValue("@ObjectType", 1);
256
257
                        insertCommand.ExecuteNonQuery();
258
                    }
259
                }
260
261
                shapes.Clear();
262
263
                result = true;
264
            }
265
            catch (Exception)
266
            {
267
                throw;
268
            }
269
270
            return result;
271
        }
272
273
        public static string CompressString(string str)
274
        {
275
            string result = null;
276
277
            using (MemoryStream outStream = new MemoryStream())
278
            {
279
                using (GZipStream gzipStream = new GZipStream(outStream, CompressionMode.Compress))
280
                using (MemoryStream srcStream = new MemoryStream(Encoding.UTF8.GetBytes(str)))
281
                    srcStream.CopyTo(gzipStream);
282
283
                result = Convert.ToBase64String(outStream.ToArray());
284
            }
285
286
            return result;
287
        }
288
289
        public static bool Export(Microsoft.Office.Interop.Excel.Worksheet worksheet)
290
        {
291
            bool result = true;
292
293
            try
294
            {
295
                var connectionStr = ConnectionDialog();
296
297
                if (connectionStr != null)
298
                {
299
                    if (CreateTabile(connectionStr))
300
                    {
301
302
                        using (SqlConnection connection = new SqlConnection(connectionStr))
303
                        {
304
                            connection.Open();
305
                            Microsoft.Office.Interop.Excel.Range range = worksheet.UsedRange;
306
307
                            // SQL INSERT 쿼리 작성
308
                            string query = $"select TopLeftCell,VALUE from {tableName}";
309
310
                            // SQL 쿼리 실행
311
                            SqlCommand command = new SqlCommand(query, connection);
312
                            var read = command.ExecuteReader();
313
314
                            while (read.Read())
315
                            {
316
                                MessageBox.Show($"{read.GetString(0)} ; {read.GetString(1)}");
317
                                break;
318
                            }
319
320
                            connection.Close();
321
                            result = true;
322
                        }
323
                    }
324
                }
325
            }
326
            catch (Exception)
327
            {
328
329
                throw;
330
            }
331
332
            return result;
333
        }
334
    }
335
}
클립보드 이미지 추가 (최대 크기: 500 MB)