Click here to Skip to main content
Click here to Skip to main content

Export DataSet to Multiple Excel Sheets

By , 12 Dec 2008
 

Introduction

I was in need of exporting multiple tables in a DataSet to an Excel file with multiple sheets, and I couldn't find anything that actually works. So, I wrote one to help people who might be in the same situation. The complete code in ExcelHelper.cs is shown below.

This only works for Excel 2003 and later versions. If a table in the dataset has more than 65,000 rows, it will break it into multiple sheets for the table with sheet name (tableNameX). replaceXmlChar() function is added to escape XML reserved characters.

Limitations of the Code

It does not handle data tables with more than 256 columns (Excel 2003 column limit), and when data tables have very large rows count, it might throw OutOfMemory exception.

Using the Code

To export a DataSet, just call the ExcelHelper.ToExcel() function as follows:

 var ds = new DataSet();
            var dt = new DataTable("TableName For Sheet1");
            dt.Columns.Add("col1");
            dt.Columns.Add("col2");
            dt.Rows.Add("Value1", "Value2");

            var dt2 = new DataTable("TableName For Sheet2");
            dt2.Columns.Add("col1");
            dt2.Columns.Add("col2");
            dt2.Rows.Add("Value1", "Value2");
            ds.Tables.Add(dt);
            ds.Tables.Add(dt2);
            ExcelHelper.ToExcel(ds, "test.xls", Page.Response);      

Here is the code that does the exporting:

//ExcelHelper.cs

public class ExcelHelper
{
    //Row limits older Excel version per sheet
        const int rowLimit = 65000;

        private static string getWorkbookTemplate()
        {
            var sb = new StringBuilder();
            sb.Append("<xml version>\r\n<Workbook
		xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n");
            sb.Append(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n
		xmlns:x=\"urn:schemas- microsoft-com:office:excel\"\r\n
		xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\">\r\n");
            sb.Append(" <Styles>\r\n
		<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n
		<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>");
            sb.Append("\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>\r\n
		<Protection/>\r\n </Style>\r\n
		<Style ss:ID=\"BoldColumn\">\r\n <Font ");
            sb.Append("x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n
		<Style ss:ID=\"s62\">\r\n <NumberFormat");
            sb.Append(" ss:Format=\"@\"/>\r\n </Style>\r\n
		<Style ss:ID=\"Decimal\">\r\n
		<NumberFormat ss:Format=\"0.0000\"/>\r\n </Style>\r\n ");
            sb.Append("<Style ss:ID=\"Integer\">\r\n
		<NumberFormat ss:Format=\"0\"/>\r\n </Style>\r\n
		<Style ss:ID=\"DateLiteral\">\r\n <NumberFormat ");
            sb.Append("ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n
		<Style ss:ID=\"s28\">\r\n");
            sb.Append("<Alignment ss:Horizontal=\"Left\" ss:Vertical=\"Top\"
		ss:ReadingOrder=\"LeftToRight\" ss:WrapText=\"1\"/>\r\n");
            sb.Append("<Font x:CharSet=\"1\" ss:Size=\"9\"
		ss:Color=\"#808080\" ss:Underline=\"Single\"/>\r\n");
            sb.Append("<Interior ss:Color=\"#FFFFFF\" ss:Pattern=\"Solid\"/>

		</Style>\r\n</Styles>\r\n {0}</Workbook>");
            return sb.ToString();
        }

        private static string replaceXmlChar(string input)
        {
            input = input.Replace("&", "&");
            input = input.Replace("<", "<");
            input = input.Replace(">", ">");
            input = input.Replace("\"", """);
            input = input.Replace("'", "&apos;");
            return input;
        }

        private static string getWorksheets(DataSet source)
        {
            var sw = new StringWriter();
            if (source == null || source.Tables.Count == 0)
            {
                sw.Write("<Worksheet ss:Name=\"Sheet1\"><Table><Row>

		<Cell  ss:StyleID=\"s62\"><Data ss:Type=\"String\"></Data>
		</Cell></Row></Table></Worksheet>");
                return sw.ToString();
            }
            foreach (DataTable dt in source.Tables)
            {
                if (dt.Rows.Count == 0)
                    sw.Write("<Worksheet ss:Name=\"" + replaceXmlChar(dt.TableName) +
			"\"><Table><Row><Cell  ss:StyleID=\"s62\">

			<Data ss:Type=\"String\"></Data></Cell></Row>
			</Table></Worksheet>");
                else
                {
                    //write each row data
                    var sheetCount = 0;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if ((i % rowLimit) == 0)
                        {
                            //add close tags for previous sheet of the same data table
                            if ((i / rowLimit) > sheetCount)
                            {
                                sw.Write("</Table></Worksheet>");
                                sheetCount = (i / rowLimit);
                            }
                            sw.Write("<Worksheet ss:Name=\"" +
				replaceXmlChar(dt.TableName) +
                                     (((i / rowLimit) == 0) ? "" :
				Convert.ToString(i / rowLimit)) + "\"><Table>");
                            //write column name row
                            sw.Write("<Row>");
                            foreach (DataColumn dc in dt.Columns)
                                sw.Write(
                                    string.Format(
                                        "<Cell ss:StyleID=\"BoldColumn\">

				<Data ss:Type=\"String\">{0}</Data></Cell>",
                                        replaceXmlChar(dc.ColumnName)));
                            sw.Write("</Row>\r\n");
                        }
                        sw.Write("<Row>\r\n");
                        foreach (DataColumn dc in dt.Columns)
                            sw.Write(
                                string.Format(
                                    "<Cell ss:StyleID=\"s62\"><Data ss:Type=\"String\">

					{0}</Data></Cell>",
                                    		replaceXmlChar
					(dt.Rows[i][dc.ColumnName].ToString())));
                        sw.Write("</Row>\r\n");
                    }
                    sw.Write("</Table></Worksheet>");
                }
            }

            return sw.ToString();
        }
        public static string GetExcelXml(DataTable dtInput, string filename)
        {
            var excelTemplate = getWorkbookTemplate();
            var ds = new DataSet();
            ds.Tables.Add(dtInput.Copy());
            var worksheets = getWorksheets(ds);
            var excelXml = string.Format(excelTemplate, worksheets);
            return excelXml;
        }

        public static string GetExcelXml(DataSet dsInput, string filename)
        {
            var excelTemplate = getWorkbookTemplate();
            var worksheets = getWorksheets(dsInput);
            var excelXml = string.Format(excelTemplate, worksheets);
            return excelXml;
        }

        public static void ToExcel
		(DataSet dsInput, string filename, HttpResponse response)
        {
            var excelXml = GetExcelXml(dsInput, filename);
            response.Clear();
            response.AppendHeader("Content-Type", "application/vnd.ms-excel");
            response.AppendHeader
		("Content-disposition", "attachment; filename=" + filename);
            response.Write(excelXml);
            response.Flush();
            response.End();
        }

        public static void ToExcel
		(DataTable dtInput, string filename, HttpResponse response)
        {
            var ds = new DataSet();
            ds.Tables.Add(dtInput.Copy());
            ToExcel(ds, filename, response);
        }
    }

History

  • 7th December, 2008: Initial post
  • 8th December, 2008: Source code and article updated
  • 11th December, 2008: Source code and article updated

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ming_Lu
Software Developer Viocare
United States United States
Member
Education: Masters in Applied mathematics
 
Certification:
MCP in Asp.net
MCP in SQL Server 2008 Implementation.
 
Working Experience In .Net since 2005

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionThread Exception [modified]memberMember 99523505hrs 48mins ago 
Hello,
 
I tried utilizing your code in a project of mine, but I received the following error after doing the reponse.Flush and response.End
 
"ex = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}"
 
Any clue as to why this could be happening? I tried substituting the dataset/datatables you were creating programmatically in place of mine, but I get the same result. Not sure how to overcome this issue.
 
Update:
Additonally, if I use HttpContext.Current.ApplicationInstance.CompleteRequest() instead Response.End(), I get the following,
 
"Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed."

modified 3 hrs ago.

Questionjet4.0membernadersghir28 Jan '13 - 3:41 
Why the generated file is not recgnized neiher by the Microsoft.Jet.OLEDB.4.0 nor Microsoft.ACE.OLEDB.12.0?
QuestionHow to store the excel file to Network shared Drive instead of opening on client machinememberkeyur_parekh25 Oct '12 - 11:37 
Hi,
 
Your code works pretty fine with little modification. It works fine on client machine. But Instead of opening the excel on client machine, I need to save it on network shared directory.
 
Could you please help me to achieve this? Or any other link where I can refer to.
 
Thanks in Advance
jjk

QuestionUnable to export if there are 1 lakh records in the datasetmemberAbhishek K Gohil11 Oct '12 - 1:51 
I tried using your code to export the data in excel. I get "Out of Memory" exception if there is data more than 1 lakhs records.
Questionnot in correct format for 2010.memberTeenustar10 Oct '12 - 10:42 
hi Ming_lu,
 
When I run this code in a machine which has Office 2010, it saves the file without the .xls file extension, and when i try to open in office 2010, we get warning message saying that the file is not in the correct format as the file extension.
 
how to solve this ? and be able to open in 2010 too..
 
Thanks.
GeneralThanks For Share this artical very helpfulmembersapnapal8 Aug '12 - 22:29 
Thanks For Share this artical very helpful
GeneralMy vote of 5memberchus2425 Jun '12 - 14:43 
Excellent work!! really appreciate it
Questiondata display in gridview depend on user key in.how to export it?membermusiw12 Jun '12 - 23:11 
i try your code.its fine. but i dont understand because my datagrid is call data from database.select command.so how to display the data.right now you just add value1,value2. my data is depend on what user key in.i cannot write every sngle column and row.
 
pls help me.i have to submit the project asap :'(
 
musiw
QuestionWorks Great...ThanksmemberMember 3324275 Jun '12 - 8:29 
Man, this is awesome...Thanks Smile | :)
GeneralNicemembersivasankari ts14 May '12 - 23:28 
Thumbs Up | :thumbsup:
 

 
Really superb...solved my problem
GeneralVote of 5!membermk_ln12 Apr '12 - 11:07 
I was originally thinking that somehow inserting a page break via response.write would give me a new tab. After much searching it seems that I wouldn't be able to insert a page break via that method.
 
Your code has assisted me greatly!
 
Thanks!
GeneralMy vote of 5membermanoj kumar choubey4 Apr '12 - 23:27 
nice
GeneralThanks for this helpful codemembermonika nafdey14 Mar '12 - 19:19 
Thanks for this helpful code.. it really helped me.. Smile | :)
But I am also getting the same issue as reported by ARK Kambhampati
GeneralMy vote of 5memberProEnggSoft1 Mar '12 - 18:30 
Useful article
Questionerror message when opening text.xlsmemberMember 86927471 Mar '12 - 16:55 
Hello,
 
Very NICE post.
 
Im using your sample code without any change, when I save the file test.xls on my desktop and when I open it, I get an error message saying "The file you are trying to open, 'test.xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?"
 
I then click on Yes, and the file in Excel is working perfectly as it should, 2 worksheets are created, with correct rows and columns as coded in your code.
 
So why do I get this message? Any way to generate an excel file that would avoid getting this error?
 
Thank you,
 
Philippe
AnswerRe: error message when opening text.xlsmembercadetduke30 Mar '12 - 9:49 
It's because you're saving it as a .xls. Change it to .xlsx.
GeneralRe: error message when opening text.xlsmemberTeenustar10 Oct '12 - 10:55 
It still gives the same warning, even when I change the code to save as .xslx
GeneralMy vote of 5memberARK Kambhampati27 Feb '12 - 20:03 
it's working for me
QuestionAlternate row colormemberkinjalin29 Nov '11 - 21:02 
Excellent article. Vote of 5
 
Can you help with formatting alternate row color & Auto fit.
GeneralMy vote of 5memberFredde197728 Sep '11 - 3:50 
Helped me alot!
Questionneed help with style sheet error [modified]membertalmans26 Aug '11 - 12:47 
I get an error when download a file. The ... style\main.css cannot be found. I don't see a reference to that in the example. Where does it reference the file?
 
This line generates the error
sb.Append("\r\n");
 
Why do many attribute tags have a leading '\' character?

modified on Friday, August 26, 2011 6:59 PM

BugNot woking with Marquee taq?membermuthura120 Jun '11 - 1:39 
If Iam working with Marquee taq in my webpage , it gives an error. how to solve this problem?
By
P.Muthu raj
tr

GeneralMy vote of 5!memberFilip D'haene14 May '11 - 11:11 
Thanks for sharing! Smile | :)
QuestionCell Formatting.. Issues...?membercodingrocks13 Mar '11 - 2:24 
I have tried exporting datatables to different worksheets using your code.
 
It was working fine. Thanks for the post.
 
But however, I have done some customization on the formatting and your styling. But when I export data, some fields which holds data as Int, but column name as string, is ignores the cases you have posted.
 
So my excel sheet contains numbers stored as Text, I need to change the format.
 
Any suggestion to take care of these scenarios, in code.
 
Thanks,
CodingRocks
 
ASP.NET,C#.NET Programmer
BANGALORE
 
"Winners don't do different things. They do things differently. ...

AnswerRe: Cell Formatting.. Issues...?memberMing_Lu13 Mar '11 - 14:41 
you can try to use Excel to create the template you need, then the xml output of the template to see how things defined, then produce the xml in the code.
GeneralMy vote of 4memberpraveen_adb9 Jan '11 - 20:26 
Its Good One,i got the code ...any how ...thanks you very much
GeneralMy vote of 5memberbacoares23 Nov '10 - 4:48 
very useful.
 
Thanks for posting.
GeneralMy vote of 5memberL.H.C1 Oct '10 - 18:56 
Wonderfull
GeneralEasy alternativememberCikaPero13 Apr '10 - 22:52 
Hi,
 
there is easier way to export DataSet to Excel with GemBox.Spreadsheet Excel C# library.
 
Here is a code snippet:
// Create new ExcelFile.
var ef = new ExcelFile();
 
// Imports all the tables from DataSet to new file.
foreach (DataTable dataTable in dataSet.Tables)
{
    // Add new worksheet to the file.
    var ws = ef.Worksheets.Add(dataTable.TableName);
 
    // Insert the data from DataTable to the worksheet starting at cell "A1".
    ws.InsertDataTable(dataTable, "A1", true);
}
 
// Save the file to XLS format.
ef.SaveXls("DataSet.xls");

GeneralAuto Fit Excel ColumnsmemberMember 465177014 Jan '10 - 1:10 
I am new to Asp.net & tried ur code,i found it excellent, i had a hurdle & could not fix AutoFit in my columns using your code in my worksheets. please give some suggestion.
 
CAUCASIAN KNIVES

GeneralSys.WebForms.PageRequestManagerParserErrorExceptionmemberSteve Crochet28 Dec '09 - 9:14 
I am exporting numerous dataset tables (upwards of 30 to 40 tabs) into a excel spreadsheet. I keep returning this error
 
Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. Details Error parsing near '<xml version>
<Work'.
 
I have researched the error in great depth and nothing seems to remedy the problem. I am not sure if the problem is in the size of my export, in the UpdatePanels inability to redraw the previously viewed data because of the AsyncPostback, or is it crapping out trying to write the XML for the export. I am at a total loss. Please help, any insight would be greatly valued.
 
Steve C
GeneralRe: Sys.WebForms.PageRequestManagerParserErrorExceptionmemberMing_Lu2 Jan '10 - 3:55 
One way to pin point the problem in your case is to save the httpresponse (that is the content of Response.Write()) in xml format and open it with excel, or notepad to see if the xml file is well formed or not.
 
Anther thing you can try is replacing the update panel with a regular asp.net panel to sort out the possibility of updatepanel doing weird things.
GeneralRe: Sys.WebForms.PageRequestManagerParserErrorExceptionmemberSteve Crochet4 Jan '10 - 5:44 
Thanks for the direction on this, I removed the update panel and it does seem to be the culprit. Do you have any words of wisdom on how to manage this issue within the UpdatePanel. Since you used the term "weird things" it would lead me to believe that the issue may be a bit ellusive with the fix more difficult to determine. Any path on which way to proceed would be greatly appreciated.
 
Steve
QuestionWhat shd i use instead of var??memberBushra2812 Oct '09 - 23:12 
What shd i use instead of var??
GeneralBig File Sizemembertxshxx4 Oct '09 - 17:12 
The excel file generated for 65536 rows data (2 sheets) is about 64MB..that's too much..before using the xml method, it consumes around 5MB only. any solutions?
QuestionExport to Excel 2003 using ASP [modified]memberkaransaxena15 Jun '09 - 10:46 
I need to export a table data to excel with insert comments as we have comments in Excel.I tried adding
<Comment><ss:Data>\"Hello World\"</ss:Data></Comment>
to the getcell function in your project, but it did not work.
Please help!!!Confused | :confused:
 
modified on Wednesday, June 17, 2009 8:12 AM

GeneralHandle linefeed in cellsmemberDACS13 Mar '09 - 13:43 
Hi
is there a way to handle linie feeds inside cells?
AnswerRe: Handle linefeed in cellsmemberMing_Lu3 Apr '09 - 7:18 
By modifying the Table tag to <Table ss:ExpandedColumnCount="2" ss:ExpandedRowCount="2" x:FullColumns="1"
x:FullRows="1" ss:DefaultRowHeight="15">
you can control the line feeds.
GeneralRe: Handle linefeed in cellsmemberDACS3 Apr '09 - 21:35 
Dear Ming_Lu
 
I can't get the linefeed feature to work,
Is it possible for you to upgrade the sample project to include a cell with a linefeed.
Thanks in avance
 
Regards Claus
QuestionCan I use this class in Windows Application?memberSu Win8 Mar '09 - 4:17 
Hi,
Can I use this class in Windows Application? Please let me know ASAP. Thanks for sharing.
 
Thanks & Best Regards
Su Win
AnswerRe: Can I use this class in Windows Application?memberMing_Lu3 Apr '09 - 7:29 
You should be to use in the windows application by the changing the "HttpResponse" type to some "Stream" Type such as MemoryStream.
GeneralRe: Can I use this class in Windows Application?memberSu Win5 Apr '09 - 17:26 
Thanks a lot.
GeneralRe: Can I use this class in Windows Application?memberBushra2812 Oct '09 - 23:16 
kindly send me code if u are done with this appication for windows application as i am facing lots of errors
GeneralRe: Can I use this class in Windows Application?memberSu Win13 Oct '09 - 17:11 
I did it but i was not using this method. If you want other ways, May I know ur email address? Pls give me ur email.
GeneralRe: Can I use this class in Windows Application?membervijayalaya4 May '11 - 20:17 
hi,
 
I need the solution in the windows aplication.So please mail me the source code to chozhanvijay@gmail.com. Smile | :)
 

Thanks in Advance
Vijay
GeneralRe: Can I use this class in Windows Application?memberSu Win5 May '11 - 16:49 
I already send to you. thanks.
 
see below my coding
 
using Microsoft.Office.Core; // Office 11.0
using Excels = Microsoft.Office.Interop.Excel; //Office 11.0
namespace ImportExportApp.Classes
{
    class ImportExport : IDisposable
    {
        #region variables
        string sqlConnStr = String.Empty;
        DBManager _dbManager;   
       int rowLimit = 10000;
        string excelVersion = "8.0";
        Hashtable myHashtable;
        //for priviledge control
        public string message = string.Empty;
	#endregion
	public ImportExport()
        {
            _dbManager = new DBManager(_loginID, _SCID);
            rowLimit = Convert.ToInt32(ConfigurationManager.AppSettings["rowLimit"].ToString());
            excelVersion = ConfigurationManager.AppSettings["excelVersion"].ToString().Trim();
       }
	private string GetExcelConStr(string fileName)
	{
		string result = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + fileName + @";Extended Properties=""Excel 8.0;HDR=NO;IMEX=1""";
		if (excelVersion != "8.0")				
			result = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + @";Extended Properties=""Excel 12.0;HDR=NO;IMEX=1"";";
			//    result = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + fileName + @";Extended Properties=""Excel 12.0;HDR=YES;"""; 
			return result;
		}
        #region Import Excel Data To SQL Server
        public void ImportExcelData(string fileName)
        {
            DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
            // Connection String to Excel Workbook
	//string excelConStr = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + fileName + @";Extended Properties=""Excel 8.0;HDR=YES;""";
	string excelConStr = this.GetExcelConStr(fileName);
	//Extended Properties=HTML Import
            DbDataAdapter adapter = factory.CreateDataAdapter();
            DbCommand selectCommand = factory.CreateCommand();
            // Create Connection to Excel Workbook
            DbConnection connection = factory.CreateConnection();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
 
            int totalRecords = 0;
            int successfulRecords = 0;
            int errorRecords = 0;
            int duplicateRecords = 0;
 
            try
            {
                if (fileName != null && fileName != "")
                {
                    #region GetListOfWorkSheets
                    DataTable sheets = new DataTable();
                    sheets = this.GetWorkSheets(fileName);
                    #endregion
                    #region Retrieve from ExcelWorkSheets
                    foreach (DataRow sheet in sheets.Rows)
                    {
                        string sheetName = sheet["TABLE_NAME"].ToString();
                            //selectCommand.CommandText = "SELECT * FROM [Sheet1$]";
                            //selectCommand.CommandText = "SELECT * FROM [" + workSheetName + "$]";
			     selectCommand.CommandText = "SELECT * FROM [" + sheetName + "]";
	//selectCommand.CommandText = "SELECT * FROM [" + sheetName + "] where [ID] is not null";
	                    if (dt != null) dt = null;
                            dt = new DataTable();
                            //Connect to Excel WorkBook
                            connection.ConnectionString = excelConStr;
                            selectCommand.Connection = connection;
                            adapter.SelectCommand = selectCommand;
                            adapter.Fill(dt);
			if (dt.Rows.Count >= 1)
                            {
				if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()))
				{
				  totalRecords += dt.Rows.Count-1;
                                    this.WriteDataToSQL(dt, sheetName, ref errorRecords, ref successfulRecords, ref totalRecords, ref duplicateRecords);
				//totalRecords = successfulRecords + errorRecords;
				}
                            }   
                    }
                    if (sheets.Rows.Count>=0) 
                     this.WriteMessage(totalRecords, successfulRecords, errorRecords, duplicateRecords);
                    if (sheets != null) sheets.Dispose();
                    #endregion
                }
            }
            catch (Exception ex)
            {
                
            }
            finally
            {
                if (factory != null) factory = null;
                excelConStr = null;
                if (adapter != null) adapter.Dispose();
                if (selectCommand != null) selectCommand.Dispose();
                if (connection != null) connection.Dispose();
                if (ds != null) ds.Dispose();
                if (dt != null) dt.Dispose();
                totalRecords = 0;
                successfulRecords = 0;
                errorRecords = 0;
                duplicateRecords = 0;
                if (_dbManager != null) { _dbManager.Dispose(); _dbManager = null; }
            }
        }
 
        private void WriteDataToSQL(DataTable dt, string sheetName, ref int errorRecords, ref int successfulRecords, ref int totalRecords, ref int duplicateRecords)
        {
            #region Variables
            string ID = String.Empty;
            int AccessID = 0;
            string PassNo = String.Empty;
            string NRIC = String.Empty;
            string Name = String.Empty;
            int CompanyID = 0;
            string Nationality = String.Empty;
            string Race = String.Empty;
            string Country = String.Empty;
            string State = String.Empty;
            string PostalCode = String.Empty;
            string _address = String.Empty;
            string _gender = "G";
            string _dOB = String.Empty;
            byte[] _photo = null;
            bool _gTFlag = false;
            #endregion
            #region For Loop
            for (int row = 1; row < dt.Rows.Count; row++)
            {  try{
inputData = String.Empty;
			activeData = String.Empty;
			//read data from datatable using 
			ID = dt.Rows[row][0].ToString().Trim().Replace("'", "");
			if (String.IsNullOrEmpty(dt.Rows[row][1].ToString()) == false)
				AccessID = Convert.ToInt32(dt.Rows[row][1].ToString());
			PassNo = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][2].ToString());
NRIC = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][3].ToString());
			Name = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][4].ToString());
			if (String.IsNullOrEmpty(dt.Rows[row][5].ToString()) == false)
				char outputChar = '0';
                        Nationality = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][6].ToString());
			Race = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][7].ToString());
			Country = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][8].ToString());
			State = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][9].ToString());
			PostalCode = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][10].ToString());
			_address = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][11].ToString());
			_gender = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][12].ToString()).ToUpper();
			if (_gender != null && _gender != "")
					{
						if (_gender.Length > 1)
						{
							if (_gender.StartsWith("M"))
								_gender = "M"; //Male
							else if (_gender.StartsWith("F"))
								_gender = "F"; //Female
							else if (_gender.StartsWith("G"))
								_gender = "G"; //All     
							else _gender = "A";
						}
					}
_dOB = CheckStringIsNullOrEmptyReturnString(dt.Rows[row][13].ToString());					
			photoPath = dt.Rows[row][24].ToString();
			_photo = Utilities.GetImageFromFile(photoPath);
			//query to insert to sqlserver database
			//For DeleteFlag = 1 : delete, 0 - don't delete
			int result = 0;
			string output = "0";
			string outputResult = String.Empty;
			result = _dbManager.ImportCAUUser(ID, AccessID, PassNo, NRIC, Name, CompanyID, Nationality, Race, Country, State, _address, PostalCode, _gender, _dOB,  _photo, "0", ref output);
			#region Clear Variables
					ID = String.Empty;
					AccessID = 0;
					PassNo = String.Empty;
					NRIC = String.Empty;
					Name = String.Empty;
					CompanyID = 0;
					Nationality = String.Empty;
					Race = String.Empty;
					Country = String.Empty;
					State = String.Empty;
					PostalCode = String.Empty;
					_address = String.Empty;
					_gender = "O";
					_dOB = String.Empty;				
 
		#endregion
				}
				catch (Exception forEx)
				{
					
				}
            }
            #endregion
        }
 
        private DataTable GetWorkSheets(string fileName)
        {
            CheckExcellProcesses();
            //string conStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\My_Documents\Data.xls; Jet OLEDB:Engine Type=5;Extended Properties=Excel 8.0;";
	//string conStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + @"; Jet OLEDB:Engine Type=5;Extended Properties=Excel 8.0;";
	string conStr = GetExcelConStr(fileName);
          DataSet excelData = new DataSet();
           OleDbConnection con = new OleDbConnection(conStr);
                  con.Open();
            DataTable sheets = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { });
            con.Close();
            // kill the right process after export completed
            KillExcel();
            if (excelData != null) excelData.Dispose();
            if (con != null) con.Dispose();
            return sheets;
        }        
        #endregion
 
        #region Export SQL Data To Excel Format
        public void ExportSQLDataToExcelFormat(string fileName, string path, string imageFilePath)
        {
            // get process ids before running the excel codes
            CheckExcellProcesses();
            Excels.Application xlsApp = null;
            Excels.Workbook xlsWorkBook = null;
            Excels.Worksheet xlsWorkSheet = null;
            object oMissing = System.Reflection.Missing.Value;
            DataSet ds = new DataSet();
            int totalRows = 0;
            int index = 1;
            short j = 1;
            try
            {
 
                #region Excel File Location
		string[] tmpFileName = fileName.Trim().Split(new char[] { '.' }, 1);
		fileName = tmpFileName[0];
 
		//For MS Office 97-2003
		if (fileName.Contains(".xls") == false)
			fileName = fileName + ".xls";
		if (path.EndsWith("\\") == false)
			path = path + "\\";
		if (File.Exists(path + fileName))
					{
 
						if (fileName.EndsWith(".xls") == true)
							fileName = fileName.Remove(fileName.Length - 4, 4);
						fileName = fileName + "_" + DateTime.Today.ToString("ddMMyyyy") + ".xls";
					}
	#endregion
                #region CreateExcelApplication
                try
                {
                    //create excel application
                    xlsApp = new Excels.Application();
                    xlsApp.DisplayAlerts = false;
 
                    //create new workbook
                    xlsWorkBook = xlsApp.Workbooks.Add(true);
 
                    //Excels.Worksheets xlsWorksheets ;
                    //xlsWorkSheet = new Excels.Worksheet();
 
                    //Add a worksheet to the workbook.
                    xlsWorkSheet = (Excels.Worksheet)xlsApp.Worksheets.Add(oMissing, oMissing, oMissing, oMissing);
 
                    //Name the sheet
                    xlsWorkSheet.Name = "Sheet_" + j;
                    j++;
 
                    ////Get a reference to the first sheet of the workbook.
                    //xlsWorkSheet = (Excels.Worksheet)xlsWorkBook.Worksheets.get_Item(1);
 
                    //Activate current worksheet
                    //xlsWorkSheet.Activate();
                    ((Excels._Worksheet)xlsWorkSheet).Activate();
                }
                catch (Exception eee)
                {
                    message = "Export Failed.";
                    message += "\n\n\n";
                    message += eee.Message.ToString();
                }
                #endregion
 
               
                    ds = _dbManager.GetUserList();
                    totalRows = ds.Tables[0].Rows.Count;
              #endregion
 
                //Write Column Name in Excel
                this.WriteColumnNameInExcelWorkSheet( xlsWorkSheet);
 
                //Format header row (bold, extra row height, autofit width)
                this.FormatHeaderRowInExcelWorkSheet(xlsWorkSheet, xlsApp);
 
                #region Write Data To Excel File
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    index++;
                    if (index <= rowLimit + 1)
                    {
                        //do your insert
                        this.WriteDataToExcelWorkSheet(imageFilePath, ds.Tables[0].Rows[i], index, xlsWorkSheet);
                    }
                    else
                    {
                        // create a new worksheet and do your insert here
 
                        //Add a worksheet to the workbook.
                        xlsWorkSheet = (Excels.Worksheet)xlsApp.Worksheets.Add(oMissing, oMissing, oMissing, oMissing);
 
                        //Name the sheet
                        xlsWorkSheet.Name = "Sheet_" + j;
                        j++;
 
                        //Activate current worksheet
						//xlsWorkSheet.Activate();
						((Excels._Worksheet)xlsWorkSheet).Activate();
 
                        this.WriteColumnNameInExcelWorkSheet(xlsWorkSheet);
 
                        this.FormatHeaderRowInExcelWorkSheet(xlsWorkSheet, xlsApp);
 
                        index = 2;
                        this.WriteDataToExcelWorkSheet(imageFilePath, ds.Tables[0].Rows[i], index, xlsWorkSheet);
 
                    }
                }
                #endregion
 
                //FormatDataRowsInExcelWorkSheet
                this.FormatDataRowsInExcelWorkSheet(xlsWorkSheet, index);
 
                #region Make excel workbook visible to user after all data has been added to worksheet
                try
                {
		xlsApp.DisplayAlerts = false;
                    xlsWorkBook.Close(true, path + fileName, null);
 
                    log.AuditLogActivity(Log.AccessType.CAUUser.ToString(), Log.ActionType.Export.ToString(), "Export User Completed. Total records exported : " + totalRows.ToString(), "", _loginID, _SCID);
 
                    message = "Export Completed.";
                    message += "\n\n\n";
                    message += "Total records exported : " + totalRows.ToString() + "\n\n";
}
                catch (Exception ee)
                {
                    
                }
                #endregion
 
                #region Export data to client machine
                //strhdr = "attachment;filename=" + strFile;
                //Response.Clear();
                //Response.ContentType = "application/vnd.ms-excel";
                //Response.ContentEncoding = System.Text.Encoding.Default;
                //Response.AppendHeader("Content-Disposition", strhdr);
                //Response.WriteFile(filename);
                //Response.Flush();
                //Response.Clear();
                //Response.Close();
                #endregion
 
            }
            catch (Exception ex)
            {
                
            }
            finally
            {
                // kill the right process after export completed
                KillExcel();
                try
                {
                    if (xlsApp != null)
                    {
                        xlsApp.Quit();
                        xlsApp = null;
                    }
                    if (xlsWorkBook != null) xlsWorkBook = null;
                    if (xlsWorkSheet != null) xlsWorkSheet = null;
                    if (ds != null) ds = null;
                    if (oMissing != null) oMissing = null;
                }
                catch { }
                if (_dbManager != null) { _dbManager.Dispose(); _dbManager = null; }
            }
        }
 
        private void CheckExcellProcesses()
        {
            Process[] AllProcesses = Process.GetProcessesByName("excel");
            myHashtable = new Hashtable();
            int iCount = 0;
 
            foreach (Process ExcelProcess in AllProcesses)
            {
                myHashtable.Add(ExcelProcess.Id, iCount);
                iCount = iCount + 1;
            }
            if (AllProcesses != null) { AllProcesses = null; }
        }
 
        private void KillExcel()
        {
            Process[] AllProcesses = Process.GetProcessesByName("EXCEL");
 
            // check to kill the right process
            foreach (Process ExcelProcess in AllProcesses)
            {
                if (myHashtable.ContainsKey(ExcelProcess.Id) == false)
                    ExcelProcess.Kill();
            }
 
            if (AllProcesses != null) { AllProcesses = null; }
        }
 
        #region Write Column Name in Excel WorkSheet
        private void WriteColumnNameInExcelWorkSheet(Excels.Worksheet xlsWorkSheet)
        {
            try
            {
                //Add table headers to worksheet
                xlsWorkSheet.Cells[1, 1] = "ID";
                xlsWorkSheet.Cells[1, 2] = "AccessID";
                xlsWorkSheet.Cells[1, 3] = "CSN";
                xlsWorkSheet.Cells[1, 4] = "NRIC";
                xlsWorkSheet.Cells[1, 5] = "Name";
                xlsWorkSheet.Cells[1, 6] = "Company Name";
                xlsWorkSheet.Cells[1, 7] = "Nationality";
                xlsWorkSheet.Cells[1, 8] = "Race";
                xlsWorkSheet.Cells[1, 9] = "Country";
                xlsWorkSheet.Cells[1, 10] = "State";
                xlsWorkSheet.Cells[1, 11] = "Postal Code";
                xlsWorkSheet.Cells[1, 12] = "Address";
                xlsWorkSheet.Cells[1, 13] = "Gender";
                xlsWorkSheet.Cells[1, 14] = "DOB";
                xlsWorkSheet.Cells[1, 15] = "Photo";
            }
            catch (Exception e1){ }
        }
        #endregion
        #region Format header row (bold, extra row height, autofit width)
        private void FormatHeaderRowInExcelWorkSheet(Excels.Worksheet xlsWorkSheet, Excels.Application xlsApp)
        {
            xlsWorkSheet.get_Range("A1", "BA1").Font.Bold = true;
	xlsWorkSheet.get_Range("A1", "BA1").Rows.RowHeight = 1.5 * xlsWorkSheet.StandardHeight;
	xlsWorkSheet.get_Range("A1", "BA1").EntireRow.AutoFit();
            //Freeze the columm headers
	xlsWorkSheet.get_Range("A2", "BA2").Select();
            xlsApp.ActiveWindow.FreezePanes = true;
        }
        #endregion
		#region Write data to Excel worksheet
		private void WriteDataToExcelWorkSheet(string imageFilePath, DataRow dr, int index, Excels.Worksheet xlsWorkSheet)
		{
			try
			{
				string ID = null;
				if (!Convert.IsDBNull(dr[0])) ID = dr[0].ToString().Trim();
				xlsWorkSheet.Cells[index, 1] =  "'" + ID;
 
				if (!Convert.IsDBNull(dr[1])) xlsWorkSheet.Cells[index, 2] = dr[1];
				if (!Convert.IsDBNull(dr[2])) xlsWorkSheet.Cells[index, 3] = dr[2].ToString().Trim();
				if (!Convert.IsDBNull(dr[3])) xlsWorkSheet.Cells[index, 4] = dr[3].ToString().Trim();
				if (!Convert.IsDBNull(dr[4])) xlsWorkSheet.Cells[index, 5] = dr[4].ToString().Trim();
				//for CompanyID
				if (!Convert.IsDBNull(dr[5])) //xlsWorkSheet.Cells[index, 6] = dr[5].ToString().Trim();
					xlsWorkSheet.Cells[index, 6] = _dbManager.GetCompanyNameByID(dr[5].ToString().Trim());
 
				if (!Convert.IsDBNull(dr[6])) xlsWorkSheet.Cells[index, 7] = dr[6].ToString().Trim();
				if (!Convert.IsDBNull(dr[7])) xlsWorkSheet.Cells[index, 8] = dr[7].ToString().Trim();
				if (!Convert.IsDBNull(dr[8])) xlsWorkSheet.Cells[index, 9] = dr[8].ToString().Trim();
				if (!Convert.IsDBNull(dr[9])) xlsWorkSheet.Cells[index, 10] = dr[9].ToString().Trim();
				if (!Convert.IsDBNull(dr[10])) xlsWorkSheet.Cells[index, 11] = dr[10].ToString().Trim();
				if (!Convert.IsDBNull(dr[11])) xlsWorkSheet.Cells[index, 12] = dr[11].ToString().Trim();
				//For Gender
				if (!Convert.IsDBNull(dr[12]))
				{
					string gender = dr[12].ToString().Trim().ToUpper();
					switch (gender)
					{
						case "F":
							xlsWorkSheet.Cells[index, 13] = "Female";
							gender = null;
							break;
						case "M":
							xlsWorkSheet.Cells[index, 13] = "Male";
							gender = null;
							break;
						case "G":
							xlsWorkSheet.Cells[index, 13] = "All";
							gender = null;
							break;
						default:
							xlsWorkSheet.Cells[index, 13] = "General";
							gender = null;
							break;
					}
				}
				if (!Convert.IsDBNull(dr[13])) xlsWorkSheet.Cells[index, 14] = dr[13];
				if (!Convert.IsDBNull(dr[14])) xlsWorkSheet.Cells[index, 15] = dr[14].ToString().Trim();
 
				#region for Photo
				try
				{
					byte[] imageByte = null;
					if (!Convert.IsDBNull(dr[24]))
					{
						//imageByte = dr[24].GetSqlBytes(24).Value;
						imageByte = (byte[])dr[24];
						//save the image to imageFileLocation
						string imgFileName = imageFilePath + cardID.ToString() + "_Photo.png";
						//Image image = Utilities.GetImageFromDB(imageByte);
						////image.Save(imgFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
						//image.Save(imgFileName);
						Bitmap bmp = Utilities.GetImageFromDB(imageByte);
						bmp.Save(imgFileName, System.Drawing.Imaging.ImageFormat.Png);
						bmp.Dispose();
						xlsWorkSheet.Cells[index, 15] = imgFileName; //dr[0].GetSqlBytes(24).Value;
						imageByte = null;
						if (bmp !=null) bmp = null;
						imgFileName = null;
					}
				}
				catch (Exception photoEx){				}
				#endregion
			}
			catch (Exception e)			{	}
		}
		#endregion
 
        #region Format data rows (align to center and left, autofit width and height)
        private void FormatDataRowsInExcelWorkSheet(Excels.Worksheet xlsWorkSheet, int index)
        {
           xlsWorkSheet.get_Range("A1", "BA" + index.ToString()).VerticalAlignment = Excels.XlVAlign.xlVAlignCenter;
		   xlsWorkSheet.get_Range("A1", "BA" + index.ToString()).HorizontalAlignment = Excels.XlHAlign.xlHAlignLeft;
		   xlsWorkSheet.get_Range("A1", "BA" + index.ToString()).EntireColumn.AutoFit();
		   xlsWorkSheet.get_Range("A1", "BA" + index.ToString()).EntireRow.AutoFit();
        }
        #endregion
        #endregion
 
        #region Write the Error record into Error log
        public void WriteToErrorLogFile(string fileName, string inputLogFile, string inputData)
        {
            string errorFile = errorFolder + fileName + ".err";// "ImportUser.err";
 
            StreamWriter swError = new StreamWriter(@errorFile, true);
            swError.WriteLine(inputLogFile);
            swError.WriteLine(inputData);
            swError.WriteLine(" ");
            swError.Flush();
            swError.Close();
        }
        #endregion
 
        #region Write the successful record into activity log
        public void WriteToAcitvityLogFile(string fileName, string inputData)
        {
            string logFile = activeFolder + fileName + ".log";
            StreamWriter swError1;
            swError1 = new StreamWriter(@logFile, true);
            swError1.WriteLine(inputData);
            swError1.WriteLine(" ");
            swError1.Flush();
            swError1.Close();
        }
        #endregion
 
        #region Validation
        private int CheckStringIsNullOrEmpty(string str)
        {
            int result = 0;
            if (String.IsNullOrEmpty(str) == false)
                result = Convert.ToInt32(str);
            return result;
        }
 
        private string CheckStringIsNullOrEmptyReturnString(string str)
        {
            string result =String.Empty ;
            if (String.IsNullOrEmpty(str) == false)
                result = Convert.ToString(str).Trim().Replace("'","`");
            return result;
        }
 
        private bool CheckStringIsNullOrEmptyReturnBool(string str)
        {
            bool result = false;
            if (String.IsNullOrEmpty(str) == false)
                result = Convert.ToBoolean(str);
            return result;
        }
 
        #endregion
 
        #region IDisposable Members
        /// <summary>
        /// Dispose Method
        /// </summary>
        public void Dispose()
        {
            sqlConnStr = String.Empty;
            if (_dbManager != null) {_dbManager.Dispose(); _dbManager=null;}
            if (debug != null) {debug.Dispose(); debug =null;}
            if (log != null) { log.Dispose(); log = null; }
 
            folderPath = String.Empty;
            errorFolder = String.Empty;
            activeFolder = String.Empty;
            rowLimit = 0;
            //workSheetName = null;
 
            if (myHashtable != null) myHashtable = null;
        }
        #endregion
	}
}

GeneralRe: Can I use this class in Windows Application?membersankar43211 Dec '11 - 22:20 
i need that code for win form
GeneralOutOfMemory problem.memberKenial8 Feb '09 - 16:01 
You offered me cool codes to meet my situation. thanks!
 
But this codes often makes an OutOfMemory exception, as you mentioned, so I altered your codes like this :
 

private static string getWorksheet(DataTable dt, int index, int cntToProceed)
{
var sw = new StringWriter();
if (dt == null)
{
sw.Write("<Worksheet ss:Name=\"Sheet1\">\r\n<Table>\r\n<Row><Cell><Data ss:Type=\"String\"></Data></Cell></Row>\r\n</Table>\r\n</Worksheet>");
return sw.ToString();
}
if (dt.Rows.Count == 0)
sw.Write("<Worksheet ss:Name=\"" + replaceXmlChar(dt.TableName) + "\">\r\n<Table>\r\n<Row><Cell ss:StyleID=\"s62\"><Data ss:Type=\"String\"></Data></Cell></Row>\r\n</Table>\r\n</Worksheet>");
else
{
//write each row data
int sheetCount = index / rowLimit;
int i = 0;
for (i = index; i < dt.Rows.Count && i < cntToProceed+index; i++)
{
if ((i % rowLimit) == 0)
{
//add close tags for previous sheet of the same data table
if (sheetCount!=0)
{
sw.Write("\r\n</Table>\r\n</Worksheet>");
sheetCount = (i / rowLimit);
}
sw.Write("\r\n<Worksheet ss:Name=\"" + replaceXmlChar(dt.TableName) +
(((i / rowLimit) == 0) ? "" : Convert.ToString(i / rowLimit)) + "\">\r\n<Table>");
//write column name row
sw.Write("\r\n<Row>");
foreach (DataColumn dc in dt.Columns)
sw.Write(string.Format("<Cell ss:StyleID=\"s62\"><Data ss:Type=\"String\">{0}</Data></Cell>", replaceXmlChar(dc.ColumnName)));
sw.Write("</Row>");
}
sw.Write("\r\n<Row>");
foreach (DataColumn dc in dt.Columns)
sw.Write(getCell(dc.DataType, dt.Rows[i][dc.ColumnName]));
sw.Write("</Row>");
}
if (i >= dt.Rows.Count)
sw.Write("\r\n</Table>\r\n</Worksheet>");
}
return sw.ToString();
}
 
public static void ToExcel(DataTable dtInput, string filename, HttpResponse response)
{
response.Clear();
response.AppendHeader("Content-Type", "application/vnd.ms-excel");
response.AppendHeader("Content-disposition", "attachment; filename=" + filename);
response.Write(getWorkbookTemplateHead());

// Record count to process at once.
int cntToProceed = 10000;
for (int i = 0; i < dtInput.Rows.Count; i += cntToProceed)
{
response.Write(getWorksheet(dtInput, i, cntToProceed));
response.Flush();
}
response.Write(getWorkbookTemplateTail());
response.End();
}
 

It's somewhat dirty code, but I think that you could understand my intention.
GeneralColors and others formatmembermmuekk16 Jan '09 - 0:47 
Hi,
 
is there any chance to export also the gridview layout/format such colors, borders, font style?
 
muek
GeneralRe: Colors and others formatmemberMember 20363832 Apr '09 - 22:27 
Hi mmuekk.
can you tell me if you could put styles to the excel sheets? and how??
 
Thank you

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 12 Dec 2008
Article Copyright 2008 by Ming_Lu
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid