Creating excel for large data in C#












0















I am trying to generate excel sheet for a large data about a million records. But when using the below code I am getting nothing. The code hangs up after line : wb.SaveAs(MyMemoryStream);. I am using closed XML for the purpose. Can you please guide what can be done to save large data as excel.



My Code:



private void DownloadExcel()
{
String Attachment = "attachment; filename=TestFile.xlsx";
Response.ClearContent();
DataTable dt = ds.Tables[0];


using (XLWorkbook wb = new XLWorkbook())

{
wb.Worksheets.Add(dt, "Data");
wb.Style.Font.FontName = "Courier New";
// wb.Cell("A1:A+" + colCount + "").Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", Attachment);
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
}


I am ok with any other library as well to save the data as XML.










share|improve this question























  • Does the code work for at least one record?

    – B001ᛦ
    Nov 14 '18 at 11:51













  • Yes this is working fine for fewer records like till 50000. When I try to create file with larger records its getting hanged or in other words not going to next line after : wb.SaveAs(MyMemoryStream);

    – Anirudh Agarwal
    Nov 14 '18 at 11:58











  • What version of Excel? Because older versions had a row limit of about 65000. Also, it'd be worth trying a different numbers of records to see your limit of where things start to go wrong.

    – Nanhydrin
    Nov 14 '18 at 11:59













  • What Nanhydrin said is the problem in your case, perhaps!

    – Syed
    Nov 14 '18 at 12:00








  • 1





    For 1 Mio Records, I highly doubt Excel is a good solution. Can the resultset be split reasonably into smaller sets that you could export to different sheets?

    – Fildor
    Nov 14 '18 at 12:19


















0















I am trying to generate excel sheet for a large data about a million records. But when using the below code I am getting nothing. The code hangs up after line : wb.SaveAs(MyMemoryStream);. I am using closed XML for the purpose. Can you please guide what can be done to save large data as excel.



My Code:



private void DownloadExcel()
{
String Attachment = "attachment; filename=TestFile.xlsx";
Response.ClearContent();
DataTable dt = ds.Tables[0];


using (XLWorkbook wb = new XLWorkbook())

{
wb.Worksheets.Add(dt, "Data");
wb.Style.Font.FontName = "Courier New";
// wb.Cell("A1:A+" + colCount + "").Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", Attachment);
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
}


I am ok with any other library as well to save the data as XML.










share|improve this question























  • Does the code work for at least one record?

    – B001ᛦ
    Nov 14 '18 at 11:51













  • Yes this is working fine for fewer records like till 50000. When I try to create file with larger records its getting hanged or in other words not going to next line after : wb.SaveAs(MyMemoryStream);

    – Anirudh Agarwal
    Nov 14 '18 at 11:58











  • What version of Excel? Because older versions had a row limit of about 65000. Also, it'd be worth trying a different numbers of records to see your limit of where things start to go wrong.

    – Nanhydrin
    Nov 14 '18 at 11:59













  • What Nanhydrin said is the problem in your case, perhaps!

    – Syed
    Nov 14 '18 at 12:00








  • 1





    For 1 Mio Records, I highly doubt Excel is a good solution. Can the resultset be split reasonably into smaller sets that you could export to different sheets?

    – Fildor
    Nov 14 '18 at 12:19
















0












0








0








I am trying to generate excel sheet for a large data about a million records. But when using the below code I am getting nothing. The code hangs up after line : wb.SaveAs(MyMemoryStream);. I am using closed XML for the purpose. Can you please guide what can be done to save large data as excel.



My Code:



private void DownloadExcel()
{
String Attachment = "attachment; filename=TestFile.xlsx";
Response.ClearContent();
DataTable dt = ds.Tables[0];


using (XLWorkbook wb = new XLWorkbook())

{
wb.Worksheets.Add(dt, "Data");
wb.Style.Font.FontName = "Courier New";
// wb.Cell("A1:A+" + colCount + "").Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", Attachment);
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
}


I am ok with any other library as well to save the data as XML.










share|improve this question














I am trying to generate excel sheet for a large data about a million records. But when using the below code I am getting nothing. The code hangs up after line : wb.SaveAs(MyMemoryStream);. I am using closed XML for the purpose. Can you please guide what can be done to save large data as excel.



My Code:



private void DownloadExcel()
{
String Attachment = "attachment; filename=TestFile.xlsx";
Response.ClearContent();
DataTable dt = ds.Tables[0];


using (XLWorkbook wb = new XLWorkbook())

{
wb.Worksheets.Add(dt, "Data");
wb.Style.Font.FontName = "Courier New";
// wb.Cell("A1:A+" + colCount + "").Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", Attachment);
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
}


I am ok with any other library as well to save the data as XML.







c# excel closedxml






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 14 '18 at 11:48









Anirudh AgarwalAnirudh Agarwal

3452521




3452521













  • Does the code work for at least one record?

    – B001ᛦ
    Nov 14 '18 at 11:51













  • Yes this is working fine for fewer records like till 50000. When I try to create file with larger records its getting hanged or in other words not going to next line after : wb.SaveAs(MyMemoryStream);

    – Anirudh Agarwal
    Nov 14 '18 at 11:58











  • What version of Excel? Because older versions had a row limit of about 65000. Also, it'd be worth trying a different numbers of records to see your limit of where things start to go wrong.

    – Nanhydrin
    Nov 14 '18 at 11:59













  • What Nanhydrin said is the problem in your case, perhaps!

    – Syed
    Nov 14 '18 at 12:00








  • 1





    For 1 Mio Records, I highly doubt Excel is a good solution. Can the resultset be split reasonably into smaller sets that you could export to different sheets?

    – Fildor
    Nov 14 '18 at 12:19





















  • Does the code work for at least one record?

    – B001ᛦ
    Nov 14 '18 at 11:51













  • Yes this is working fine for fewer records like till 50000. When I try to create file with larger records its getting hanged or in other words not going to next line after : wb.SaveAs(MyMemoryStream);

    – Anirudh Agarwal
    Nov 14 '18 at 11:58











  • What version of Excel? Because older versions had a row limit of about 65000. Also, it'd be worth trying a different numbers of records to see your limit of where things start to go wrong.

    – Nanhydrin
    Nov 14 '18 at 11:59













  • What Nanhydrin said is the problem in your case, perhaps!

    – Syed
    Nov 14 '18 at 12:00








  • 1





    For 1 Mio Records, I highly doubt Excel is a good solution. Can the resultset be split reasonably into smaller sets that you could export to different sheets?

    – Fildor
    Nov 14 '18 at 12:19



















Does the code work for at least one record?

– B001ᛦ
Nov 14 '18 at 11:51







Does the code work for at least one record?

– B001ᛦ
Nov 14 '18 at 11:51















Yes this is working fine for fewer records like till 50000. When I try to create file with larger records its getting hanged or in other words not going to next line after : wb.SaveAs(MyMemoryStream);

– Anirudh Agarwal
Nov 14 '18 at 11:58





Yes this is working fine for fewer records like till 50000. When I try to create file with larger records its getting hanged or in other words not going to next line after : wb.SaveAs(MyMemoryStream);

– Anirudh Agarwal
Nov 14 '18 at 11:58













What version of Excel? Because older versions had a row limit of about 65000. Also, it'd be worth trying a different numbers of records to see your limit of where things start to go wrong.

– Nanhydrin
Nov 14 '18 at 11:59







What version of Excel? Because older versions had a row limit of about 65000. Also, it'd be worth trying a different numbers of records to see your limit of where things start to go wrong.

– Nanhydrin
Nov 14 '18 at 11:59















What Nanhydrin said is the problem in your case, perhaps!

– Syed
Nov 14 '18 at 12:00







What Nanhydrin said is the problem in your case, perhaps!

– Syed
Nov 14 '18 at 12:00






1




1





For 1 Mio Records, I highly doubt Excel is a good solution. Can the resultset be split reasonably into smaller sets that you could export to different sheets?

– Fildor
Nov 14 '18 at 12:19







For 1 Mio Records, I highly doubt Excel is a good solution. Can the resultset be split reasonably into smaller sets that you could export to different sheets?

– Fildor
Nov 14 '18 at 12:19














1 Answer
1






active

oldest

votes


















0














You can try any of below approaches:



Approach 1: First you need to create the template of the excel and then use the below function. It will create new excel using your template and inserts data into excel using ACE.OLEDB. It will be much faster but you don't have control over formatting.



   public static void CopyDataTableToExcel(DataTable dtExcel, String excelOutputTemplate, string outExcelPath)
{
File.Copy(excelOutputTemplate, outExcelPath, true);

string qryFieldName = "";
string qryFieldForCreate = "";
string qryFieldValue = "";
string qryFieldValueTemp = "";
string qryInsert = "";

for (int i = 0; i < dtExcel.Columns.Count; i++)
{
qryFieldName = qryFieldName + (qryFieldName.Trim() != "" ? ", " : "") + "[" + dtExcel.Columns[i].ColumnName + "]";
qryFieldForCreate = qryFieldForCreate + (qryFieldForCreate.Trim() != "" ? ", " : "") +
"[" + dtExcel.Columns[i].ColumnName + "] varchar(255)";
}

// Establish a connection to the data source.
System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + outExcelPath + "';Extended Properties="Excel 12.0;HDR=YES;"");
objConn.Open();

// Add two records to the table named 'MyTable'.
System.Data.OleDb.OleDbCommand objCmd = new System.Data.OleDb.OleDbCommand();
objCmd.Connection = objConn;

qryInsert = "Create table InventorySheet (" + qryFieldForCreate + ")";
objCmd.CommandText = qryInsert;
objCmd.ExecuteNonQuery();

for (int i = 0; i < dtExcel.Rows.Count; i++)
{
qryFieldValue = "";
for (int j = 0; j < dtExcel.Columns.Count; j++)
{
qryFieldValueTemp = dtExcel.Rows[i][j].ToString();
if (qryFieldValueTemp.Length > 255)
{
qryFieldValueTemp = qryFieldValueTemp.Substring(qryFieldValueTemp.Length - 255);
}
qryFieldValue = qryFieldValue + (qryFieldValue.Trim() != "" ? ", '" : "'") + qryFieldValueTemp.Replace("'", "''") + "'";
}

//qryInsert = "Insert into [Sheet1$] Values (" + qryFieldValue + ")";
qryInsert = "Insert into InventorySheet (" + qryFieldName + ") Values (" + qryFieldValue + ")";
objCmd.CommandText = qryInsert;
objCmd.ExecuteNonQuery();
}

// Close the connection.
objConn.Close();
MessageBox.Show("Exported successfully.");
}


Approach 2: Serialize the data table into xml:



DataTable dtJobMetaData = yourDataSet.Tables["PDF"];
dtJobMetaData.WriteXml(xmlPath);





share|improve this answer
























  • Parameterize your SQL!

    – user2366842
    Nov 14 '18 at 14:53











  • This is done when we already have the excel file on the user machine. What to do if we have to give them option download?

    – Anirudh Agarwal
    Nov 15 '18 at 7:44











  • You don't need to have excel installed on user machine. You can create a template on the machine where excel is installed and put that excel in your solution directory.

    – Brijesh Kumar Tripathi
    Nov 15 '18 at 10:45











  • Please see File.Copy method in the function. It uses excel as a database and add table into it and inserts data into newly created excel using your template. I am using this approach.

    – Brijesh Kumar Tripathi
    Nov 15 '18 at 10:53











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53299552%2fcreating-excel-for-large-data-in-c-sharp%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














You can try any of below approaches:



Approach 1: First you need to create the template of the excel and then use the below function. It will create new excel using your template and inserts data into excel using ACE.OLEDB. It will be much faster but you don't have control over formatting.



   public static void CopyDataTableToExcel(DataTable dtExcel, String excelOutputTemplate, string outExcelPath)
{
File.Copy(excelOutputTemplate, outExcelPath, true);

string qryFieldName = "";
string qryFieldForCreate = "";
string qryFieldValue = "";
string qryFieldValueTemp = "";
string qryInsert = "";

for (int i = 0; i < dtExcel.Columns.Count; i++)
{
qryFieldName = qryFieldName + (qryFieldName.Trim() != "" ? ", " : "") + "[" + dtExcel.Columns[i].ColumnName + "]";
qryFieldForCreate = qryFieldForCreate + (qryFieldForCreate.Trim() != "" ? ", " : "") +
"[" + dtExcel.Columns[i].ColumnName + "] varchar(255)";
}

// Establish a connection to the data source.
System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + outExcelPath + "';Extended Properties="Excel 12.0;HDR=YES;"");
objConn.Open();

// Add two records to the table named 'MyTable'.
System.Data.OleDb.OleDbCommand objCmd = new System.Data.OleDb.OleDbCommand();
objCmd.Connection = objConn;

qryInsert = "Create table InventorySheet (" + qryFieldForCreate + ")";
objCmd.CommandText = qryInsert;
objCmd.ExecuteNonQuery();

for (int i = 0; i < dtExcel.Rows.Count; i++)
{
qryFieldValue = "";
for (int j = 0; j < dtExcel.Columns.Count; j++)
{
qryFieldValueTemp = dtExcel.Rows[i][j].ToString();
if (qryFieldValueTemp.Length > 255)
{
qryFieldValueTemp = qryFieldValueTemp.Substring(qryFieldValueTemp.Length - 255);
}
qryFieldValue = qryFieldValue + (qryFieldValue.Trim() != "" ? ", '" : "'") + qryFieldValueTemp.Replace("'", "''") + "'";
}

//qryInsert = "Insert into [Sheet1$] Values (" + qryFieldValue + ")";
qryInsert = "Insert into InventorySheet (" + qryFieldName + ") Values (" + qryFieldValue + ")";
objCmd.CommandText = qryInsert;
objCmd.ExecuteNonQuery();
}

// Close the connection.
objConn.Close();
MessageBox.Show("Exported successfully.");
}


Approach 2: Serialize the data table into xml:



DataTable dtJobMetaData = yourDataSet.Tables["PDF"];
dtJobMetaData.WriteXml(xmlPath);





share|improve this answer
























  • Parameterize your SQL!

    – user2366842
    Nov 14 '18 at 14:53











  • This is done when we already have the excel file on the user machine. What to do if we have to give them option download?

    – Anirudh Agarwal
    Nov 15 '18 at 7:44











  • You don't need to have excel installed on user machine. You can create a template on the machine where excel is installed and put that excel in your solution directory.

    – Brijesh Kumar Tripathi
    Nov 15 '18 at 10:45











  • Please see File.Copy method in the function. It uses excel as a database and add table into it and inserts data into newly created excel using your template. I am using this approach.

    – Brijesh Kumar Tripathi
    Nov 15 '18 at 10:53
















0














You can try any of below approaches:



Approach 1: First you need to create the template of the excel and then use the below function. It will create new excel using your template and inserts data into excel using ACE.OLEDB. It will be much faster but you don't have control over formatting.



   public static void CopyDataTableToExcel(DataTable dtExcel, String excelOutputTemplate, string outExcelPath)
{
File.Copy(excelOutputTemplate, outExcelPath, true);

string qryFieldName = "";
string qryFieldForCreate = "";
string qryFieldValue = "";
string qryFieldValueTemp = "";
string qryInsert = "";

for (int i = 0; i < dtExcel.Columns.Count; i++)
{
qryFieldName = qryFieldName + (qryFieldName.Trim() != "" ? ", " : "") + "[" + dtExcel.Columns[i].ColumnName + "]";
qryFieldForCreate = qryFieldForCreate + (qryFieldForCreate.Trim() != "" ? ", " : "") +
"[" + dtExcel.Columns[i].ColumnName + "] varchar(255)";
}

// Establish a connection to the data source.
System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + outExcelPath + "';Extended Properties="Excel 12.0;HDR=YES;"");
objConn.Open();

// Add two records to the table named 'MyTable'.
System.Data.OleDb.OleDbCommand objCmd = new System.Data.OleDb.OleDbCommand();
objCmd.Connection = objConn;

qryInsert = "Create table InventorySheet (" + qryFieldForCreate + ")";
objCmd.CommandText = qryInsert;
objCmd.ExecuteNonQuery();

for (int i = 0; i < dtExcel.Rows.Count; i++)
{
qryFieldValue = "";
for (int j = 0; j < dtExcel.Columns.Count; j++)
{
qryFieldValueTemp = dtExcel.Rows[i][j].ToString();
if (qryFieldValueTemp.Length > 255)
{
qryFieldValueTemp = qryFieldValueTemp.Substring(qryFieldValueTemp.Length - 255);
}
qryFieldValue = qryFieldValue + (qryFieldValue.Trim() != "" ? ", '" : "'") + qryFieldValueTemp.Replace("'", "''") + "'";
}

//qryInsert = "Insert into [Sheet1$] Values (" + qryFieldValue + ")";
qryInsert = "Insert into InventorySheet (" + qryFieldName + ") Values (" + qryFieldValue + ")";
objCmd.CommandText = qryInsert;
objCmd.ExecuteNonQuery();
}

// Close the connection.
objConn.Close();
MessageBox.Show("Exported successfully.");
}


Approach 2: Serialize the data table into xml:



DataTable dtJobMetaData = yourDataSet.Tables["PDF"];
dtJobMetaData.WriteXml(xmlPath);





share|improve this answer
























  • Parameterize your SQL!

    – user2366842
    Nov 14 '18 at 14:53











  • This is done when we already have the excel file on the user machine. What to do if we have to give them option download?

    – Anirudh Agarwal
    Nov 15 '18 at 7:44











  • You don't need to have excel installed on user machine. You can create a template on the machine where excel is installed and put that excel in your solution directory.

    – Brijesh Kumar Tripathi
    Nov 15 '18 at 10:45











  • Please see File.Copy method in the function. It uses excel as a database and add table into it and inserts data into newly created excel using your template. I am using this approach.

    – Brijesh Kumar Tripathi
    Nov 15 '18 at 10:53














0












0








0







You can try any of below approaches:



Approach 1: First you need to create the template of the excel and then use the below function. It will create new excel using your template and inserts data into excel using ACE.OLEDB. It will be much faster but you don't have control over formatting.



   public static void CopyDataTableToExcel(DataTable dtExcel, String excelOutputTemplate, string outExcelPath)
{
File.Copy(excelOutputTemplate, outExcelPath, true);

string qryFieldName = "";
string qryFieldForCreate = "";
string qryFieldValue = "";
string qryFieldValueTemp = "";
string qryInsert = "";

for (int i = 0; i < dtExcel.Columns.Count; i++)
{
qryFieldName = qryFieldName + (qryFieldName.Trim() != "" ? ", " : "") + "[" + dtExcel.Columns[i].ColumnName + "]";
qryFieldForCreate = qryFieldForCreate + (qryFieldForCreate.Trim() != "" ? ", " : "") +
"[" + dtExcel.Columns[i].ColumnName + "] varchar(255)";
}

// Establish a connection to the data source.
System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + outExcelPath + "';Extended Properties="Excel 12.0;HDR=YES;"");
objConn.Open();

// Add two records to the table named 'MyTable'.
System.Data.OleDb.OleDbCommand objCmd = new System.Data.OleDb.OleDbCommand();
objCmd.Connection = objConn;

qryInsert = "Create table InventorySheet (" + qryFieldForCreate + ")";
objCmd.CommandText = qryInsert;
objCmd.ExecuteNonQuery();

for (int i = 0; i < dtExcel.Rows.Count; i++)
{
qryFieldValue = "";
for (int j = 0; j < dtExcel.Columns.Count; j++)
{
qryFieldValueTemp = dtExcel.Rows[i][j].ToString();
if (qryFieldValueTemp.Length > 255)
{
qryFieldValueTemp = qryFieldValueTemp.Substring(qryFieldValueTemp.Length - 255);
}
qryFieldValue = qryFieldValue + (qryFieldValue.Trim() != "" ? ", '" : "'") + qryFieldValueTemp.Replace("'", "''") + "'";
}

//qryInsert = "Insert into [Sheet1$] Values (" + qryFieldValue + ")";
qryInsert = "Insert into InventorySheet (" + qryFieldName + ") Values (" + qryFieldValue + ")";
objCmd.CommandText = qryInsert;
objCmd.ExecuteNonQuery();
}

// Close the connection.
objConn.Close();
MessageBox.Show("Exported successfully.");
}


Approach 2: Serialize the data table into xml:



DataTable dtJobMetaData = yourDataSet.Tables["PDF"];
dtJobMetaData.WriteXml(xmlPath);





share|improve this answer













You can try any of below approaches:



Approach 1: First you need to create the template of the excel and then use the below function. It will create new excel using your template and inserts data into excel using ACE.OLEDB. It will be much faster but you don't have control over formatting.



   public static void CopyDataTableToExcel(DataTable dtExcel, String excelOutputTemplate, string outExcelPath)
{
File.Copy(excelOutputTemplate, outExcelPath, true);

string qryFieldName = "";
string qryFieldForCreate = "";
string qryFieldValue = "";
string qryFieldValueTemp = "";
string qryInsert = "";

for (int i = 0; i < dtExcel.Columns.Count; i++)
{
qryFieldName = qryFieldName + (qryFieldName.Trim() != "" ? ", " : "") + "[" + dtExcel.Columns[i].ColumnName + "]";
qryFieldForCreate = qryFieldForCreate + (qryFieldForCreate.Trim() != "" ? ", " : "") +
"[" + dtExcel.Columns[i].ColumnName + "] varchar(255)";
}

// Establish a connection to the data source.
System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + outExcelPath + "';Extended Properties="Excel 12.0;HDR=YES;"");
objConn.Open();

// Add two records to the table named 'MyTable'.
System.Data.OleDb.OleDbCommand objCmd = new System.Data.OleDb.OleDbCommand();
objCmd.Connection = objConn;

qryInsert = "Create table InventorySheet (" + qryFieldForCreate + ")";
objCmd.CommandText = qryInsert;
objCmd.ExecuteNonQuery();

for (int i = 0; i < dtExcel.Rows.Count; i++)
{
qryFieldValue = "";
for (int j = 0; j < dtExcel.Columns.Count; j++)
{
qryFieldValueTemp = dtExcel.Rows[i][j].ToString();
if (qryFieldValueTemp.Length > 255)
{
qryFieldValueTemp = qryFieldValueTemp.Substring(qryFieldValueTemp.Length - 255);
}
qryFieldValue = qryFieldValue + (qryFieldValue.Trim() != "" ? ", '" : "'") + qryFieldValueTemp.Replace("'", "''") + "'";
}

//qryInsert = "Insert into [Sheet1$] Values (" + qryFieldValue + ")";
qryInsert = "Insert into InventorySheet (" + qryFieldName + ") Values (" + qryFieldValue + ")";
objCmd.CommandText = qryInsert;
objCmd.ExecuteNonQuery();
}

// Close the connection.
objConn.Close();
MessageBox.Show("Exported successfully.");
}


Approach 2: Serialize the data table into xml:



DataTable dtJobMetaData = yourDataSet.Tables["PDF"];
dtJobMetaData.WriteXml(xmlPath);






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 14 '18 at 14:38









Brijesh Kumar TripathiBrijesh Kumar Tripathi

14519




14519













  • Parameterize your SQL!

    – user2366842
    Nov 14 '18 at 14:53











  • This is done when we already have the excel file on the user machine. What to do if we have to give them option download?

    – Anirudh Agarwal
    Nov 15 '18 at 7:44











  • You don't need to have excel installed on user machine. You can create a template on the machine where excel is installed and put that excel in your solution directory.

    – Brijesh Kumar Tripathi
    Nov 15 '18 at 10:45











  • Please see File.Copy method in the function. It uses excel as a database and add table into it and inserts data into newly created excel using your template. I am using this approach.

    – Brijesh Kumar Tripathi
    Nov 15 '18 at 10:53



















  • Parameterize your SQL!

    – user2366842
    Nov 14 '18 at 14:53











  • This is done when we already have the excel file on the user machine. What to do if we have to give them option download?

    – Anirudh Agarwal
    Nov 15 '18 at 7:44











  • You don't need to have excel installed on user machine. You can create a template on the machine where excel is installed and put that excel in your solution directory.

    – Brijesh Kumar Tripathi
    Nov 15 '18 at 10:45











  • Please see File.Copy method in the function. It uses excel as a database and add table into it and inserts data into newly created excel using your template. I am using this approach.

    – Brijesh Kumar Tripathi
    Nov 15 '18 at 10:53

















Parameterize your SQL!

– user2366842
Nov 14 '18 at 14:53





Parameterize your SQL!

– user2366842
Nov 14 '18 at 14:53













This is done when we already have the excel file on the user machine. What to do if we have to give them option download?

– Anirudh Agarwal
Nov 15 '18 at 7:44





This is done when we already have the excel file on the user machine. What to do if we have to give them option download?

– Anirudh Agarwal
Nov 15 '18 at 7:44













You don't need to have excel installed on user machine. You can create a template on the machine where excel is installed and put that excel in your solution directory.

– Brijesh Kumar Tripathi
Nov 15 '18 at 10:45





You don't need to have excel installed on user machine. You can create a template on the machine where excel is installed and put that excel in your solution directory.

– Brijesh Kumar Tripathi
Nov 15 '18 at 10:45













Please see File.Copy method in the function. It uses excel as a database and add table into it and inserts data into newly created excel using your template. I am using this approach.

– Brijesh Kumar Tripathi
Nov 15 '18 at 10:53





Please see File.Copy method in the function. It uses excel as a database and add table into it and inserts data into newly created excel using your template. I am using this approach.

– Brijesh Kumar Tripathi
Nov 15 '18 at 10:53


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53299552%2fcreating-excel-for-large-data-in-c-sharp%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Bressuire

Vorschmack

Quarantine