Click here to Skip to main content
15,888,022 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to export to excel from datatable and format the excel file in format the excel file dynamically.

Like : font change, color change from ditterent cell dynamically

What I have tried:

i have tried using string writer using \n and \t.
Posted
Updated 9-Jan-19 10:00am
Comments
F-ES Sitecore 9-Jan-19 6:01am    
Google "c# create excel file" and you'll find lots of examples.

You can try the EPPlus library, see answers here: Export datatable to excel in C#[^]
 
Share this answer
 
You cannot create an Excel file using stringwriter. Excel file content uses a special structure that must be accessed either using OLEDB (see Working with MS Excel(xls / xlsx) Using MDAC and Oledb[^] ) or the Microsoft.Office.Interop.Excel Namespace | Microsoft Docs[^] .
 
Share this answer
 
Excel export would be tougher (there is a lot of formatting that goes along with it). On the simpler side... you can create it as a CSV (comma separated value file).

StringBuilder sb = new StringBuilder(); 

string[] columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToArray();
sb.AppendLine(string.Join(",", columnNames));

foreach (DataRow row in dt.Rows)
{
    string[] fields = row.ItemArray.Select(field => field.ToString()).ToArray();
    sb.AppendLine(string.Join(",", fields));
}

File.WriteAllText("output.csv", sb.ToString());
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900