■ SqlMapper 클래스의 GetRowParser 확장 메소드를 사용해 제네릭 타입 데이터의 .CSV 파일을 생성하는 방법을 보여준다.
▶ MainForm.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.IO; using System.Text; using DevExpress.Utils; using DevExpress.XtraEditors; using DevExpress.XtraGrid.Views.Grid; using Dapper; namespace TestProject { /// <summary> /// 메인 폼 /// </summary> public partial class MainForm : XtraForm { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 연결 /// </summary> private OleDbConnection connection; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - MainForm() /// <summary> /// 생성자 /// </summary> public MainForm() { InitializeComponent(); this.connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=nwind.mdb"); this.gridView.InitializeView ( true, // Multi Select GridMultiSelectMode.CellSelect, // Grid Multi Select Mode DrawFocusRectStyle.CellFocus, // Draw Focus Rect Style true, // Show Indicator true, // Show Column Headers true, // Allow Column Moving true, // Allow Column Resizing true, // Allow Filter true, // Allow Sort false, // Allow Cell Merge EditorShowMode.Default, // Editor Show Mode false // Editable ); this.gridView.OptionsBehavior.AutoPopulateColumns = true; this.gridControl.DataSource = Order.GetOrderList(this.connection); this.gridView.BestFitColumns(); this.createButton.Click += createButton_Click; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Private //////////////////////////////////////////////////////////////////////////////// Event #region 생성하기 버튼 클릭시 처리하기 - createButton_Click(sender, e) /// <summary> /// 생성하기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> private void createButton_Click(object sender, EventArgs e) { string sql = "SELECT * FROM Orders"; WriteFile(this.connection, sql, null, 500, "D:\\", "Sample"); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 헤더 라인 쓰기 - WriteHeaderLine(writer, rowDictionary) /// <summary> /// 헤더 라인 쓰기 /// </summary> /// <param name="writer">스트림 라이터</param> /// <param name="rowDictionary">행 딕셔너리</param> private void WriteHeaderLine(StreamWriter writer, IDictionary<string, object> rowDictionary) { int x = 0; foreach(KeyValuePair<string, object> keyValuePair in rowDictionary) { if(x > 0) { writer.Write(","); } if(x < rowDictionary.Count - 1) { writer.Write(keyValuePair.Key); } else { writer.WriteLine(keyValuePair.Key); } x++; } } #endregion #region 데이터 라인 쓰기 - WriteDataLine(writer, rowDictionary) /// <summary> /// 데이터 라인 쓰기 /// </summary> /// <param name="writer">스트림 라이터</param> /// <param name="rowDictionary">행 딕셔너리</param> private void WriteDataLine(StreamWriter writer, IDictionary<string, object> rowDictionary) { int x = 0; foreach(KeyValuePair<string, object> keyValuePair in rowDictionary) { if(x > 0) { writer.Write(","); } object valueObject = keyValuePair.Value; if(valueObject == null) { #region 값 객체가 NULL인 경우 처리한다. if(x < rowDictionary.Count - 1) { writer.Write(string.Empty); } else { writer.WriteLine(string.Empty); } #endregion } else { Type valueObjectType = valueObject?.GetType(); if(valueObjectType == typeof(DateTime)) { #region 값 객체 타입이 DateTime인 경우 처리한다. DateTime valueDateTime = (DateTime)valueObject; if(x < rowDictionary.Count - 1) { writer.Write(valueDateTime.ToString("yyyy-MM-dd HH:mm:ss")); } else { writer.WriteLine(valueDateTime.ToString("yyyy-MM-dd HH:mm:ss")); } #endregion } else if(valueObjectType == typeof(DateTime?)) { #region 값 객체 타입이 DateTime?인 경우 처리한다. DateTime? valueDateTime = (DateTime?)valueObject; if(valueDateTime.HasValue) { if(x < rowDictionary.Count - 1) { writer.Write(valueDateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")); } else { writer.WriteLine(valueDateTime.Value.ToString("yyyy-MM-dd HH:mm:ss")); } } else { if(x < rowDictionary.Count - 1) { writer.Write(string.Empty); } else { writer.WriteLine(string.Empty); } } #endregion } else if(valueObjectType == typeof(string)) { #region 값 객체 타입이 string인 경우 처리한다. string valueString = (string)valueObject; if(valueString == null) { if(x < rowDictionary.Count - 1) { writer.Write(string.Empty); } else { writer.WriteLine(string.Empty); } } else { if(x < rowDictionary.Count - 1) { writer.Write($"\"{valueString.Replace("\r", string.Empty).Replace("\n", string.Empty)}\""); } else { writer.WriteLine($"\"{valueString.Replace("\r", string.Empty).Replace("\n", string.Empty)}\""); } } #endregion } else { #region 값 객체 타입이 기타인 경우 처리한다. if(x < rowDictionary.Count - 1) { writer.Write(valueObject); } else { writer.WriteLine(valueObject); } #endregion } } x++; } } #endregion #region 파일 쓰기 - WriteFile(connection, sql, condition, lineCountPerFile, saveDirectoryPath, fileName) /// <summary> /// 파일 쓰기 /// </summary> /// <param name="connection">연결</param> /// <param name="sql">SQL</param> /// <param name="condition">조건</param> /// <param name="lineCountPerFile">파일당 라인 수</param> /// <param name="saveDirectoryPath">저장 디렉토리 경로</param> /// <param name="fileName">파일 확장자가 없는 파일명</param> private void WriteFile(IDbConnection connection, string sql, object condition, int lineCountPerFile, string saveDirectoryPath, string fileName) { using(IDataReader reader = connection.ExecuteReader(sql, condition)) { int lineCount = 0; StreamWriter writer = null; try { while(reader.Read()) { int rest = lineCount % lineCountPerFile; if(rest == 0) { writer?.Dispose(); int sequence = lineCount / lineCountPerFile + 1; string actualFileName = $"{fileName}_{sequence}.csv"; string actualFilePath = Path.Combine(saveDirectoryPath, actualFileName); writer = new StreamWriter(actualFilePath, false, Encoding.UTF8); } var rowParser = reader.GetRowParser<dynamic>(); var row = rowParser(reader); IDictionary<string, object> rowDictionary = row as IDictionary<string, object>; if(rest == 0) { WriteHeaderLine(writer, rowDictionary); } WriteDataLine(writer, rowDictionary); lineCount++; } if(lineCount == 0) { string actualFileName = $"{fileName}_1.csv"; string actualFilePath = Path.Combine(saveDirectoryPath, actualFileName); writer = new StreamWriter(actualFilePath, false, Encoding.UTF8); } } finally { writer?.Dispose(); } } } #endregion } } |