Professional Documents
Culture Documents
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;
namespace ExportToExcel
{
//
// November 2013
// http://www.mikesknowledgebase.com
//
// Note: if you plan to use this in an ASP.Net 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
// - 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.
//
#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(DataTable dt, string filename,
System.Web.HttpResponse Response)
{
try
{
DataSet ds = new DataSet();
ds.Tables.Add(dt);
CreateExcelDocumentAsStream(ds, filename, Response);
ds.Tables.Remove(dt);
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 = "";
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.AddHeader("content-disposition", "attachment; filename=" +
filename);
Response.ContentType = "application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet";
byte[] data1 = new byte[stream.Length];
stream.Read(data1, 0, data1.Length);
stream.Close();
Response.BinaryWrite(data1);
Response.Flush();
Response.End();
return true;
}
catch (Exception ex)
{
Trace.WriteLine("Failed, exception thrown: " + ex.Message);
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 document =
SpreadsheetDocument.Create(excelFilename, SpreadsheetDocumentType.Workbook))
{
WriteExcelFile(ds, document);
}
Trace.WriteLine("Successfully created: " + excelFilename);
return true;
}
catch (Exception ex)
{
Trace.WriteLine("Failed, exception thrown: " + ex.Message);
return false;
}
}
WorksheetPart newWorksheetPart =
spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new
DocumentFormat.OpenXml.Spreadsheet.Worksheet();
// save worksheet
WriteDataTableToExcelWorksheet(dt, newWorksheetPart);
newWorksheetPart.Worksheet.Save();
spreadsheet.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.
Sheets>().AppendChild(new DocumentFormat.OpenXml.Spreadsheet.Sheet()
{
Id = spreadsheet.WorkbookPart.GetIdOfPart(newWorksheetPart),
SheetId = (uint)worksheetNumber,
Name = dt.TableName
});
worksheetNumber++;
}
spreadsheet.WorkbookPart.Workbook.Save();
}
// 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[] IsNumericColumn = new bool[numberOfColumns];
//
// Create the Header row in our Excel Worksheet
//
uint rowIndex = 1;
//
// Now, step through each row of data in our DataTable...
//
double cellNumericValue = 0;
foreach (DataRow dr in dt.Rows)
{
// ...create a new row, and append a set of this row's data to it.
++rowIndex;
var newExcelRow = new Row { RowIndex = rowIndex }; // add a row at
the top of spreadsheet
sheetData.Append(newExcelRow);