-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCreateExcelFile.cs
519 lines (462 loc) · 22.9 KB
/
CreateExcelFile.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
//#define INCLUDE_WEB_FUNCTIONS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Data;
using System.Reflection;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using System.Globalization;
using System.Text.RegularExpressions;
namespace ExportToExcel
{
//
// January 2022
// http://www.mikesknowledgebase.com
//
// Note: if you plan to use this in an ASP.Net web application, remember to add a reference to "System.Web", and to uncomment
// the "INCLUDE_WEB_FUNCTIONS" definition at the top of this file.
//
// Release history
// - Sep 2016:
// Make sure figures with a decimal part are formatted with a full-stop as a decimal point.
// - Feb 2015:
// Needed to replace "Response.End();" with some other code, to make sure the Excel was fully written to the HTTP Response
// New ReplaceHexadecimalSymbols() function to prevent hex characters from crashing the export.
// Changed GetExcelColumnName() to cope with more than 702 columns (!)
// - Jan 2015:
// Throwing an exception when trying to export a DateTime containing null.
// Was missing the function declaration for "CreateExcelDocument(DataSet ds, string filename, System.Web.HttpResponse Response)"
// Removed the "Response.End();" from the web version, as recommended in: https://support.microsoft.com/kb/312629/EN-US/?wa=wsignin1.0
// - Mar 2014:
// Now writes the Excel data using the OpenXmlWriter classes, which are much more memory efficient.
// - Nov 2013:
// Changed "CreateExcelDocument(DataTable dt, string xlsxFilePath)" to remove the DataTable from the DataSet after creating the Excel file.
// You can now create an Excel file via a Stream (making it more ASP.Net friendly)
// - Jan 2013: Fix: Couldn't open .xlsx files using OLEDB (was missing "WorkbookStylesPart" part)
// - Nov 2012:
// List<>s with Nullable columns weren't be handled properly.
// If a value in a numeric column doesn't have any data, don't write anything to the Excel file (previously, it'd write a '0')
// - Jul 2012: Fix: Some worksheets weren't exporting their numeric data properly, causing "Excel found unreadable content in '___.xslx'" errors.
// - Mar 2012: Fixed issue, where Microsoft.ACE.OLEDB.12.0 wasn't able to connect to the Excel files created using this class.
//
//
// (c) www.mikesknowledgebase.com 2022
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
public class CreateExcelFile
{
public static bool CreateExcelDocument<T>(List<T> list, string xlsxFilePath)
{
DataSet ds = new DataSet();
ds.Tables.Add(ListToDataTable(list));
return CreateExcelDocument(ds, xlsxFilePath);
}
#region HELPER_FUNCTIONS
// This function is adapated from: http://www.codeguru.com/forum/showthread.php?t=450171
// My thanks to Carl Quirion, for making it "nullable-friendly".
public static DataTable ListToDataTable<T>(List<T> list)
{
DataTable dt = new DataTable();
var props = typeof(T).GetProperties().Where(p => p.GetIndexParameters().Length == 0).ToList();
foreach (PropertyInfo info in props)
{
dt.Columns.Add(new DataColumn(info.Name, GetNullableType(info.PropertyType)));
}
foreach (T t in list)
{
DataRow row = dt.NewRow();
foreach (PropertyInfo info in props)
{
if (!IsNullableType(info.PropertyType))
row[info.Name] = info.GetValue(t, null);
else
row[info.Name] = (info.GetValue(t, null) ?? DBNull.Value);
}
dt.Rows.Add(row);
}
return dt;
}
private static Type GetNullableType(Type t)
{
Type returnType = t;
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
returnType = Nullable.GetUnderlyingType(t);
}
return returnType;
}
private static bool IsNullableType(Type type)
{
return (type == typeof(string) ||
type.IsArray ||
(type.IsGenericType &&
type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))));
}
public static bool CreateExcelDocument(DataTable dt, string xlsxFilePath)
{
DataSet ds = new DataSet();
ds.Tables.Add(dt);
bool result = CreateExcelDocument(ds, xlsxFilePath);
ds.Tables.Remove(dt);
return result;
}
#endregion
#if INCLUDE_WEB_FUNCTIONS
/// <summary>
/// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file)
/// </summary>
/// <param name="dt">DataTable containing the data to be written to the Excel.</param>
/// <param name="filename">The filename (without a path) to call the new Excel file.</param>
/// <param name="Response">HttpResponse of the current page.</param>
/// <returns>True if it was created succesfully, otherwise false.</returns>
public static bool CreateExcelDocument(DataSet ds, string filename, System.Web.HttpResponse Response)
{
try
{
CreateExcelDocumentAsStream(ds, filename, Response);
return true;
}
catch (Exception ex)
{
Trace.WriteLine("Failed, exception thrown: " + ex.Message);
return false;
}
}
public static bool CreateExcelDocument(DataTable dt, string filename, System.Web.HttpResponse Response)
{
try
{
DataSet ds = new DataSet();
ds.Tables.Add(dt);
CreateExcelDocument(ds, filename, Response);
ds.Tables.Remove(dt);
return true;
}
catch (Exception ex)
{
Trace.WriteLine("Failed, exception thrown: " + ex.Message);
return false;
}
}
public static bool CreateExcelDocument<T>(List<T> list, string filename, System.Web.HttpResponse Response)
{
try
{
DataSet ds = new DataSet();
ds.Tables.Add(ListToDataTable(list));
CreateExcelDocumentAsStream(ds, filename, Response);
return true;
}
catch (Exception ex)
{
Trace.WriteLine("Failed, exception thrown: " + ex.Message);
return false;
}
}
/// <summary>
/// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file)
/// </summary>
/// <param name="ds">DataSet containing the data to be written to the Excel.</param>
/// <param name="filename">The filename (without a path) to call the new Excel file.</param>
/// <param name="Response">HttpResponse of the current page.</param>
/// <returns>Either a MemoryStream, or NULL if something goes wrong.</returns>
public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response)
{
try
{
System.IO.MemoryStream stream = new System.IO.MemoryStream();
using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true))
{
WriteExcelFile(ds, document);
}
stream.Flush();
stream.Position = 0;
Response.ClearContent();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
// NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have
// manually added System.Web to this project's References.
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.AddHeader("content-disposition", "attachment; filename=" + filename);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("content-length", stream.Length.ToString());
byte[] data1 = new byte[stream.Length];
stream.Read(data1, 0, data1.Length);
stream.Close();
Response.BinaryWrite(data1);
Response.Flush();
// Feb2015: Needed to replace "Response.End();" with the following 3 lines, to make sure the Excel was fully written to the Response
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.SuppressContent = true;
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
return true;
}
catch (Exception ex)
{
Trace.WriteLine("Failed, exception thrown: " + ex.Message);
// Display an error on the webpage.
System.Web.UI.Page page = System.Web.HttpContext.Current.CurrentHandler as System.Web.UI.Page;
page.ClientScript.RegisterStartupScript(page.GetType(), "log", "console.log('Failed, exception thrown: " + ex.Message + "')", true);
return false;
}
}
#endif // End of "INCLUDE_WEB_FUNCTIONS" section
/// <summary>
/// Create an Excel file, and write it to a file.
/// </summary>
/// <param name="ds">DataSet containing the data to be written to the Excel.</param>
/// <param name="excelFilename">Name of file to be written.</param>
/// <returns>True if successful, false if something went wrong.</returns>
public static bool CreateExcelDocument(DataSet ds, string excelFilename)
{
try
{
using (SpreadsheetDocument spreadsheet = SpreadsheetDocument.Create(excelFilename, SpreadsheetDocumentType.Workbook))
{
WriteExcelFile(ds, spreadsheet);
}
Trace.WriteLine("Successfully created: " + excelFilename);
return true;
}
catch (Exception ex)
{
Trace.WriteLine("Failed, exception thrown: " + ex.Message);
return false;
}
}
private static void WriteExcelFile(DataSet ds, SpreadsheetDocument spreadsheet)
{
// Create the Excel file contents. This function is used when creating an Excel file either writing
// to a file, or writing to a MemoryStream.
spreadsheet.AddWorkbookPart();
spreadsheet.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
// My thanks to James Miera for the following line of code (which prevents crashes in Excel 2010)
spreadsheet.WorkbookPart.Workbook.Append(new BookViews(new WorkbookView()));
// If we don't add a "WorkbookStylesPart", OLEDB will refuse to connect to this .xlsx file !
WorkbookStylesPart workbookStylesPart = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>("rIdStyles");
Stylesheet stylesheet = new Stylesheet();
workbookStylesPart.Stylesheet = stylesheet;
// Loop through each of the DataTables in our DataSet, and create a new Excel Worksheet for each.
uint worksheetNumber = 1;
Sheets sheets = spreadsheet.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
foreach (DataTable dt in ds.Tables)
{
// For each worksheet you want to create
string worksheetName = dt.TableName;
// Create worksheet part, and add it to the sheets collection in workbook
WorksheetPart newWorksheetPart = spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>();
Sheet sheet = new Sheet() { Id = spreadsheet.WorkbookPart.GetIdOfPart(newWorksheetPart), SheetId = worksheetNumber, Name = worksheetName };
// If you want to define the Column Widths for a Worksheet, you need to do this *before* appending the SheetData
// http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/1d93eca8-2949-4d12-8dd9-15cc24128b10/
sheets.Append(sheet);
// Append this worksheet's data to our Workbook, using OpenXmlWriter, to prevent memory problems
WriteDataTableToExcelWorksheet(dt, newWorksheetPart);
worksheetNumber++;
}
spreadsheet.WorkbookPart.Workbook.Save();
}
private static void WriteDataTableToExcelWorksheet(DataTable dt, WorksheetPart worksheetPart)
{
OpenXmlWriter writer = OpenXmlWriter.Create(worksheetPart, Encoding.ASCII);
writer.WriteStartElement(new Worksheet());
writer.WriteStartElement(new SheetData());
string cellValue = "";
string cellReference = "";
// Create a Header Row in our Excel file, containing one header for each Column of data in our DataTable.
//
// We'll also create an array, showing which type each column of data is (Text or Numeric), so when we come to write the actual
// cells of data, we'll know if to write Text values or Numeric cell values.
int numberOfColumns = dt.Columns.Count;
bool[] IsIntegerColumn = new bool[numberOfColumns];
bool[] IsFloatColumn = new bool[numberOfColumns];
bool[] IsDateColumn = new bool[numberOfColumns];
string[] excelColumnNames = new string[numberOfColumns];
for (int n = 0; n < numberOfColumns; n++)
excelColumnNames[n] = GetExcelColumnName(n);
//
// Create the Header row in our Excel Worksheet
//
uint rowIndex = 1;
writer.WriteStartElement(new Row { RowIndex = rowIndex });
for (int colInx = 0; colInx < numberOfColumns; colInx++)
{
DataColumn col = dt.Columns[colInx];
AppendHeaderTextCell(excelColumnNames[colInx] + "1", col.ColumnName, writer);
IsIntegerColumn[colInx] = (col.DataType.FullName.StartsWith("System.Int"));
IsFloatColumn[colInx] = (col.DataType.FullName == "System.Decimal") || (col.DataType.FullName == "System.Double") || (col.DataType.FullName == "System.Single");
IsDateColumn[colInx] = (col.DataType.FullName == "System.DateTime");
}
writer.WriteEndElement(); // End of header "Row"
//
// Now, step through each row of data in our DataTable...
//
double cellFloatValue = 0;
CultureInfo ci = new CultureInfo("en-US");
foreach (DataRow dr in dt.Rows)
{
// ...create a new row, and append a set of this row's data to it.
++rowIndex;
writer.WriteStartElement(new Row { RowIndex = rowIndex });
for (int colInx = 0; colInx < numberOfColumns; colInx++)
{
cellValue = dr.ItemArray[colInx].ToString();
cellValue = ReplaceHexadecimalSymbols(cellValue);
cellReference = excelColumnNames[colInx] + rowIndex.ToString();
// Create cell with data
if (IsIntegerColumn[colInx] || IsFloatColumn[colInx])
{
// For numeric cells without any decimal places.
// If this numeric value is NULL, then don't write anything to the Excel file.
cellFloatValue = 0;
if (double.TryParse(cellValue, out cellFloatValue))
{
cellValue = cellFloatValue.ToString(ci);
AppendNumericCell(cellReference, cellValue, writer);
}
}
else if (IsDateColumn[colInx])
{
// This is a date value.
DateTime dateValue;
if (DateTime.TryParse(cellValue, out dateValue))
{
AppendDateCell(cellReference, dateValue, writer);
}
else
{
// This should only happen if we have a DataColumn of type "DateTime", but this particular value is null/blank.
AppendTextCell(cellReference, cellValue, writer);
}
}
else
{
// For text cells, just write the input data straight out to the Excel file.
AppendTextCell(cellReference, cellValue, writer);
}
}
writer.WriteEndElement(); // End of Row
}
writer.WriteEndElement(); // End of SheetData
writer.WriteEndElement(); // End of worksheet
writer.Close();
}
private static void AppendHeaderTextCell(string cellReference, string cellStringValue, OpenXmlWriter writer)
{
// Add a new "text" Cell to the first row in our Excel worksheet
// We set these cells to use "Style # 3", so they have a gray background color & white text.
writer.WriteElement(new Cell
{
CellValue = new CellValue(cellStringValue),
CellReference = cellReference,
DataType = CellValues.String
});
}
private static void AppendTextCell(string cellReference, string cellStringValue, OpenXmlWriter writer)
{
// Add a new "text" Cell to our Row
#if DATA_CONTAINS_FORMULAE
// If this item of data looks like a formula, let's store it in the Excel file as a formula rather than a string.
if (cellStringValue.StartsWith("="))
{
AppendFormulaCell(cellReference, cellStringValue, writer);
return;
}
#endif
// Add a new Excel Cell to our Row
writer.WriteElement(new Cell
{
CellValue = new CellValue(cellStringValue),
CellReference = cellReference,
DataType = CellValues.String
});
}
private static void AppendDateCell(string cellReference, DateTime dateTimeValue, OpenXmlWriter writer)
{
// Add a new "datetime" Excel Cell to our Row.
//
string cellStringValue = dateTimeValue.ToShortDateString();
writer.WriteElement(new Cell
{
CellValue = new CellValue(cellStringValue),
CellReference = cellReference,
DataType = CellValues.String
});
}
private static void AppendFormulaCell(string cellReference, string cellStringValue, OpenXmlWriter writer)
{
// Add a new "formula" Excel Cell to our Row
writer.WriteElement(new Cell
{
CellFormula = new CellFormula(cellStringValue),
CellReference = cellReference,
DataType = CellValues.Number
});
}
private static void AppendNumericCell(string cellReference, string cellStringValue, OpenXmlWriter writer)
{
// Add a new numeric Excel Cell to our Row.
writer.WriteElement(new Cell
{
CellValue = new CellValue(cellStringValue),
CellReference = cellReference,
DataType = CellValues.Number
});
}
private static string ReplaceHexadecimalSymbols(string txt)
{
string r = "[\x00-\x08\x0B\x0C\x0E-\x1F\x26]";
return Regex.Replace(txt, r, "", RegexOptions.Compiled);
}
// Convert a zero-based column index into an Excel column reference (A, B, C.. Y, Y, AA, AB, AC... AY, AZ, B1, B2..)
public static string GetExcelColumnName(int columnIndex)
{
// eg (0) should return "A"
// (1) should return "B"
// (25) should return "Z"
// (26) should return "AA"
// (27) should return "AB"
// ..etc..
char firstChar;
char secondChar;
char thirdChar;
if (columnIndex < 26)
{
return ((char)('A' + columnIndex)).ToString();
}
if (columnIndex < 702)
{
firstChar = (char)('A' + (columnIndex / 26) - 1);
secondChar = (char)('A' + (columnIndex % 26));
return string.Format("{0}{1}", firstChar, secondChar);
}
int firstInt = columnIndex / 676;
int secondInt = (columnIndex % 676) / 26;
if (secondInt == 0)
{
secondInt = 26;
firstInt = firstInt - 1;
}
int thirdInt = (columnIndex % 26);
firstChar = (char)('A' + firstInt - 1);
secondChar = (char)('A' + secondInt - 1);
thirdChar = (char)('A' + thirdInt);
return string.Format("{0}{1}{2}", firstChar, secondChar, thirdChar);
}
}
}